gpt4 book ai didi

python - update_or_create 的 Django GenericRelation

转载 作者:行者123 更新时间:2023-12-01 00:47:22 31 4
gpt4 key购买 nike

我在将 GenericRelationupdate_or_create 结合使用时遇到问题。我有以下型号:

class LockCode(TimeStampedModel):
context_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
context_id = models.PositiveIntegerField()
context = GenericForeignKey('context_type', 'context_id')


class Mission(DirtyFieldsMixin, models.Model):
lock_codes = GenericRelation(
LockCode,
content_type_field='context_type',
object_id_field='context_id',
related_query_name='mission'
)

我尝试使用任务作为 key 来创建或更新 LockCode:

mission = ....
LockCode.objects.update_or_create(
context=mission,
defaults={
#some other columns there
}

而且我有FieldError:字段“上下文”不会生成自动反向关系,因此不能用于反向查询。如果是 GenericForeignKey,请考虑添加 GenericRelation。

当我显式使用 context_id 和 context_type 时它会起作用:

LockCode.objects.update_or_create(
context_id=mission.pk,
context_type=ContentType.objects.get_for_model(Mission),
defaults={
#some other columns there
}

我的配置有问题吗?或者它只是使用 GenericForeignKey 进行 update_or_create 的单一方法?

最佳答案

找到了解决方案。只需要在 update_or_create 中使用 mission 而不是 context 即可:

mission = ....
LockCode.objects.update_or_create(
mission=mission,
defaults={
#some other columns there
}

关于python - update_or_create 的 Django GenericRelation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56855817/

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