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?

Paweł Kłeczek
  • 603
  • 1
  • 5
  • 28
  • 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. – tutuca Feb 21 '15 at 14:44

1 Answers1

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
MrKsn
  • 1,185
  • 1
  • 16
  • 27
  • 3
    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 – rgammans Aug 25 '16 at 21:00