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