gpt4 book ai didi

Django GenericForeignKey 更新

转载 作者:行者123 更新时间:2023-12-04 01:53:53 37 4
gpt4 key购买 nike

我正在尝试在 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_typeobject_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()

最佳答案

没有理由在这里使用过滤器和更新。你已经有了对象。

for comment in comments:
comment.content_object = comment.post
comment.save()

关于Django GenericForeignKey 更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51670468/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com