I want to create data migrations for a model(Comment
) which has a GenericForeignKey
relation. My model was made according to django documentation for 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 to add comments to any 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 I run ./manage.py migrate
I get:
TypeError: 'content_object' is an invalid keyword argument for this function
I have to say that I have used same code as create_comment
inside a view and works well.
Im using django 1.7.7. Im not using south.
Edit: I 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 be a "ContentType" instance.