Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.
like image 749
Laraconda Avatar asked Oct 31 '15 00:10

Laraconda


1 Answers

As I said, I've been through this same problem and a colleague helped me with this tip:

You really need to set content_type and object_pk as +Shang Wang pointed out, but ContentType must be loaded using apps.get_model instead of directly import it.

So use this:

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

In your migration method and all 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
    )
like image 165
Rafael Verger Avatar answered Nov 14 '22 21:11

Rafael Verger