【发布时间】:2018-09-19 18:34:39
【问题描述】:
我有一个具有通用关系的相当基本的 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 是 TextField 以支持相关对象(例如 UUID)上的非整数 PK。此模型往往与各种其他模型相关,因此它需要在支持的 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 错误,还是我持有错误?
【问题讨论】:
标签: python django postgresql django-orm