Django GenericRelation for the update_or_create



我在将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'
    )

我尝试使用任务作为密钥创建或更新LockCode

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

我有FieldError: Field 'context' does not generate an automatic reverse relation and therefore cannot be used for reverse querying. If it is a GenericForeignKey, consider adding a 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
            }

相关内容

  • 没有找到相关文章

最新更新