用于update_or_create的Django GenericRelation

时间:2019-07-02 15:33:10

标签: 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'
    )

我尝试使用任务作为密钥来创建或更新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的唯一方法?

1 个答案:

答案 0 :(得分:2)

找到了解决方案。只需使用mission代替context进入update_or_create:

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