Unable to create model instance using GenericForeignKey during migration

IMPORTANT: This question is no longer relevant.


In Django 1.7 migration, I am trying to create Commentary comments programmatically 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 an error occurs: 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 an empty model using new = Comment() and then set all the required fields manually, but even if I set the content_type and object_pk respectively, they were not actually saved by content_type , and I got 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 shared foreign key when migrating? Or any workaround?

+5
source share
1 answer

This is a migration model loader issue. You load your default models

 Comment = apps.get_model('django_comments', 'Comment') 

It loads the Comment model in some special way, so some functions, such as general relationships, do not work.

There is a little hacky solution: download your models as usual:

 from django_comments import Comment 
+3
source

Source: https://habr.com/ru/post/1210973/


All Articles