python - update_or_create 的 Django GenericRelation

标签 python django generic-foreign-key

我在将 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/

相关文章:

html - 在 Visual Studio Code 中为 django-html 文件添加格式化程序(美化器)

python - 如何使用 Django Rest Framework 创建登录 API?

python - sqlalchemy 通用外键(就像在 django ORM 中一样)

python - 尝试从网页中提取一些数据(抓取初学者)

python - 如何更改 TLS 上下文选项

python - 如何使用 Python 将一个 CSV 中的行复制到另一个 CSV 文件

python - 是否有任何应用程序可以实时可视化 Django 应用程序中表和数据库之间的数据流?

django - 是否可以在 Django 中使用自然键作为 GenericForeignKey ?

Django GenericForeignKey 更新

python - 无法在 django 中找出正确的 json 查询集