我在将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的唯一方法?

最佳答案

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

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/

10-09 14:38