1

我在使用GenericRelationwith 时遇到问题update_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 的单一方式?

4

1 回答 1

2

找到了解决方案。只需要使用mission而不是context进入update_or_create:

mission = ....
LockCode.objects.update_or_create(
            mission=mission,
            defaults={
             #some other columns there
            }
于 2019-07-02T17:36:31.677 回答