Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create an instance of a model with GenericForeignKey in migration

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?

like image 450
Paweł Kłeczek Avatar asked Oct 19 '22 19:10

Paweł Kłeczek


1 Answers

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
like image 66
MrKsn Avatar answered Oct 22 '22 21:10

MrKsn