6

IMPORTANT: This question is no longer relevant.


In a Django 1.7 migration I try to create Comment entries programatically with the following code:

# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
 def create_genericcomment_from_bookingcomment(apps, schema_editor):
 BookingComment = apps.get_model('booking', 'BookingComment')
 Comment = apps.get_model('django_comments', 'Comment')
 for comment in BookingComment.objects.all():
 new = Comment(content_object=comment.booking)
 new.save()
 dependencies = [
 ('comments', '0001_initial'),
 ('django_comments', '__first__'),
 ]
 operations = [
 migrations.RunPython(create_genericcomment_from_bookingcomment),
 ]

And it produces an error: TypeError: 'content_object' is an invalid keyword argument for this function

However, the same code (i.e. Comment(content_object=comment.booking)) works when executed in the shell.

I tried to create a blank model with new = Comment() and then set all the necessary fields manually but even though I set content_type and object_pk fields accordingly, they content_type was not actually saved and I received django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint

Any idea how to properly create a model with a generic foreign key in a migration? Or any workaround?

asked Jan 13, 2015 at 10:59
1
  • Can you paste the models? At least the relevant bit? I'm running into the same situation trying to create a simple model that is the target of a M2M field. The model itself has no relation field. Commented Feb 21, 2015 at 14:44

1 Answer 1

3

This is an issue of migrations' model loader. You load your models using default

Comment = apps.get_model('django_comments', 'Comment')

It loads the Comment model in some special way, so some features like generic relations don't work.

There is a bit hacky solution: load your models as usual:

from django_comments import Comment
answered Mar 3, 2015 at 13:14
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately this isn't even a solution. It works until you add a field to Comment; at that point during migration the upto date model generates SQL for the schema version which is to be applied in a later migration. So any long term project which has older database hanging around can no longer apply ir migrations

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.