我想为Comment
具有GenericForeignKey
关系的模型()创建数据迁移。我的模型是根据django的contenttypes文档制作的。
楷模:
...
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')
数据迁移:
...
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)
]
当我跑步时,./manage.py migrate
我得到:
TypeError: 'content_object' is an invalid keyword argument for this function
我不得不说我使用create_comment
了与视图内部相同的代码并且运行良好。
我使用 django 1.7.7。我不使用南方。
编辑: 我试过尚王的回答。
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
)
也不工作:
ValueError: Cannot assign "<ContentType: nice meme>": "Comment.content_type" must be a "ContentType" instance.