【发布时间】:2018-08-03 10:17:43
【问题描述】:
我正在尝试在 django 中将 ForeignKey 转换为 GenericForeignKey。我计划在三个迁移中执行此操作,mig1、mig2、mig3。
迁移1(mig1)有如下代码
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('post_service', '0008_auto_20180802_1112'),
]
operations = [
migrations.AddField(
model_name='comment',
name='content_type',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='contenttypes.ContentType'),
),
migrations.AddField(
model_name='comment',
name='object_id',
field=models.PositiveIntegerField(null=True),
),
]
迁移2(mig2)有如下代码
def change_posts_to_generic_key_comment(apps, schema_editor):
Comment = apps.get_model('post_service', 'Comment')
db_alias = schema_editor.connection.alias
comments = Comment.objects.using(db_alias).all()
for comment in comments:
Comment.objects.filter(id=comment.id).update(content_object=comment.post)
def reverse_change_posts_to_generic_key_comment(apps, schema_editor):
Comment = apps.get_model('post_service', 'Comment')
db_alias = schema_editor.connection.alias
comments = Comment.objects.using(db_alias).all()
for comment in comments:
Comment.objects.filter(id=comment.id).update(content_object=)
class Migration(migrations.Migration):
dependencies = [
('post_service', '0009_auto_20180802_1623'),
]
operations = [
migrations.RunPython(change_posts_to_generic_key_comment, reverse_change_posts_to_generic_key_comment),
]
我尝试同时使用对象的更新和直接分配
comment.content_object = content.post 后跟comment.save()
它们似乎都不起作用。我如何更新通用外键字段。
一种方法是手动设置content_type 和object_id。有没有更好的方法来做到这一点?
编辑:评论模型
class Comment(models.Model):
post = models.ForeignKey(Post,on_delete=models.CASCADE)
# Fields for generic relation
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True)
object_id = models.PositiveIntegerField(null=True)
content_object = GenericForeignKey()
【问题讨论】:
-
我今天遇到了这个。我的理论是发生了一些事情,因为模型实例不是模型类的 true 实例,而是
apps.get_model返回的类的实例,这是模型类在某个时刻的表示历史。但是TBH,我不知道。当我有更多时间时,我希望能进一步研究这个问题。可以通过直接在迁移中设置content_type_id和object_id来解决问题。 -
我也有同样的问题,你是如何更新 Django 中的 GenericForeignKey 字段的?
-
@codinginquarantine 我运行了一个函数,它获取模型中的所有项目并在循环中手动分配每个项目,然后分配 content_type 和 object_id 然后保存它,但效率非常低。至少我当时是这么认为的。
标签: django django-migrations generic-foreign-key