Django / PostgreSQL 与 TextField object_id 字段的一般关系
Django / PostgreSQL generic relationships with a TextField object_id field
我有一个看起来相当基本的 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 错误,还是我理解错了?
原来这其实是一个Django的bug。 https://code.djangoproject.com/ticket/16055
它已有 7 年历史,尚未提供修复。
我有一个看起来相当基本的 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 错误,还是我理解错了?
原来这其实是一个Django的bug。 https://code.djangoproject.com/ticket/16055
它已有 7 年历史,尚未提供修复。