Django / PostgreSQL 与 TextField object_id 字段的泛型关系



我有一个看起来相当基本的Django模型,具有通用关系:

class AttachedMediaItem(models.Model):
# Generic relation to another object.
parent_content_type = models.ForeignKey(
'contenttypes.ContentType',
related_name='attachedmediaitem_parent_set', on_delete=models.CASCADE)
parent_object_id = models.TextField(db_index=True)
parent_content_object = GenericForeignKey('parent_content_type',
'parent_object_id')

(删除了不相关的字段)

我继承了这个代码库,所以我不能完全证明所有设计决策的合理性,但我相信parent_object_id是支持相关对象(例如 UUID)上的非整数 PK 的一种TextField。该模型往往与各种其他模型相关,因此就其支持的PK类型而言,它需要非常通用。

这是根据 Django 文档的建议:https://docs.djangoproject.com/en/2.0/ref/contrib/contenttypes/#django.contrib.contenttypes.fields.GenericForeignKey

现在,这个模型:

class UnitType(models.Model):
media = GenericRelation('media.AttachedMediaItem',
content_type_field='parent_content_type',
object_id_field='parent_object_id')

(删除了不相关的字段)。

请注意,我将把PK生成留给Django,这意味着我将为这个模型获得一个整数PK。

现在,如果我运行这个

UnitType.objects.filter(media__isnull=True) 

SQL错误设法通过ORM冒泡:

ProgrammingError: operator does not exist: integer = text
LINE 1: ...a_attachedmediaitem" ON ("products_unittype"."id" = "media_a...
^
HINT:  No operator matches the given name and argument type(s). You might need to add explicit type casts.

我的理解是,这是由于PK字段的差异。

除了将通用对象 ID 字段类型更改为整数字段(此时不是一个真正的选项)之外 - 我有哪些选择?这被认为是一个 Django 错误,还是我拿错了?

事实证明,这实际上是一个 Django 错误。 https://code.djangoproject.com/ticket/16055

它已有 7 年的历史,没有提供任何修复。

相关内容

最新更新