5

重要:この質問はもはや関係ありません。


Django 1.7 移行では、次のコードを使用してプログラムでコメント エントリを作成しようとしています。

# -*- 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),
    ]

そして、それはエラーを生成します: TypeError: 'content_object' is an invalid keyword argument for this function

Comment(content_object=comment.booking)ただし、シェルで実行すると同じコード (つまり) が機能します。

で空のモデルを作成しnew = Comment()、必要なすべてのフィールドを手動で設定しようとしましたが、それに応じてフィールドを設定しても、実際content_typeには保存されず、受け取りましたobject_pkcontent_typedjango.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint

移行で一般的な外部キーを使用してモデルを適切に作成する方法はありますか? または回避策はありますか?

4

1 に答える 1

3

これは、移行のモデル ローダーの問題です。デフォルトを使用してモデルをロードします

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

特別な方法でモデルをロードするCommentため、一般的なリレーションなどの一部の機能は機能しません。

少しハックな解決策があります: 通常どおりモデルをロードします。

from django_comments import Comment
于 2015-03-03T13:14:52.693 に答える