python - GenericForeignKey data migtation error: 'content_object' is an invalid keyword argument -


i want create data migrations model(comment) has genericforeignkey relation. model made according django documentation contenttypes.

models:

... class nicememe(models.model):     """         example model.     """      name = models.charfield(max_length=140)     image = models.imagefield(upload_to=get_path_to_store_nice_meme_images)   class comment(models.model):     """         model add comments other (non abstract) model.     """     ...     user = models.foreignkey(extendeduser)     content = models.charfield(max_length=140)     content_type = models.foreignkey(contenttype)     object_pk = models.positiveintegerfield()     content_object = genericforeignkey('content_type', 'object_pk') 

data migration:

... def create_comment(apps, schema_editor):     ...     nice_meme = nicememe.objects.create(name='nice nice meme')     comment.objects.create(         user=user,         content='gott ist tot',         poster_username='friedrich',         content_object=nice_meme     )  ... operations = [     migrations.runpython(create_comment) ] 

when run ./manage.py migrate get:

typeerror: 'content_object' invalid keyword argument function

i have have used same code create_comment inside view , works well.

im using django 1.7.7. im not using south.

edit: tried shang wang's answer.

comment.objects.create(     user=user,     content='gott ist tot',      poster_username='friedrich',     content_type=contenttype.objects.get_for_model(nice_meme),     object_pk=nice_meme.id )  

is not working either:

valueerror: cannot assign "<contenttype: nice meme>": "comment.content_type"  must "contenttype" instance. 

as said, i've been through same problem , colleague helped me tip:

you need set content_type , object_pk +shang wang pointed out, contenttype must loaded using apps.get_model instead of directly import it.

so use this:

contenttype = apps.get_model('contenttypes', 'contenttype')

in migration method , should work :)

def create_comment(apps, schema_editor):     ...     contenttype = apps.get_model('contenttypes', 'contenttype')     nice_meme = nicememe.objects.create(name='nice nice meme')     comment.objects.create(         user=user,         content='gott ist tot',         poster_username='friedrich',         content_type=contenttype.objects.get_for_model(nice_meme),         object_pk=nice_meme.id     ) 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -