Django-Postgres:CharField 的长度作为主键
Posted
技术标签:
【中文标题】Django-Postgres:CharField 的长度作为主键【英文标题】:Django-Postgres: length of CharField as primary key 【发布时间】:2018-11-18 15:04:34 【问题描述】:在我的 Django 模型中,有一个 CharField 作为主键,有 250 个字符,如 max_length
和一个 ManyToManyField
:
class GenericRoom(models.Model):
key = models.CharField(primary_key=True, max_length=250)
name = models.CharField(max_length=500, default='')
extension = models.IntegerField(null=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, related_name="%(app_label)s_%(class)s_owner",
on_delete=models.CASCADE)
moderators = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="%(app_label)s_%(class)s_moderators",
blank=True)
type = models.CharField(max_length=50, choices=ROOM_TYPE_CHOICES, default='meeting')
class Room(GenericRoom):
pin = models.IntegerField(null=True)
另外,在 Postgres 中,key
列的最大长度为 250,如下所示:
Column | Type | Collation | Nullable | Default
---------------------+------------------------+-----------+----------+---------
key | character varying(250) | | not null |
但是,当我提供的密钥超过 50 个字符时,我正在这样做:
r=Room.objects.create(key='a_veeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeery_long_key')
r.moderators.add(User.objects.get(id=123))
我得到:
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
psycopg2.DataError: value too long for type character varying(50)
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 898, in add
self._add_items(self.source_field_name, self.target_field_name, *objs)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 1065, in _add_items
for obj_id in new_ids
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/models/query.py", line 466, in bulk_create
ids = self._batched_insert(objs_without_pk, fields, batch_size)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/models/query.py", line 1142, in _batched_insert
inserted_id = self._insert(item, fields=fields, using=self.db, return_id=True)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/models/query.py", line 1125, in _insert
return query.get_compiler(using=using).execute_sql(return_id)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/models/sql/compiler.py", line 1283, in execute_sql
cursor.execute(sql, params)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 100, in execute
return super().execute(sql, params)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 68, in execute
return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 77, in _execute_with_wrappers
return executor(sql, params, many, context)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/utils.py", line 89, in __exit__
raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/ilias/.virtualenvs/vsceneapi/local/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute
return self.cursor.execute(sql, params)
django.db.utils.DataError: value too long for type character varying(50)
对于小于 50 的键,一切正常。
因此,key
列必须有 50 个字符的隐式限制,即使限制似乎是 250。
但是为什么呢?我该如何改变呢?
编辑:
Postgres 对表格的描述是:
Column | Type | Collation | Nullable | Default
---------------------+------------------------+-----------+----------+---------
key | character varying(250) | | not null |
owner_id | integer | | |
extension | integer | | |
name | character varying(500) | | not null |
type | character varying(100) | | not null |
pexip_conference_id | integer | | |
pin | integer | | |
Indexes:
"rooms_room_pkey" PRIMARY KEY, btree (key)
"rooms_room_key_ca48250b_like" btree (key varchar_pattern_ops)
"rooms_room_owner_id_13734245" btree (owner_id)
Foreign-key constraints:
"rooms_room_owner_id_13734245_fk_users_user_id" FOREIGN KEY (owner_id) REFERENCES users_user(id) DEFERRABLE INITIALLY DEFERRED
Referenced by:
TABLE "meeting_spaces_meetingspace" CONSTRAINT "meeting_spaces_meetingspace_room_id_10905900_fk" FOREIGN KEY (room_id) REFERENCES rooms_room(key) DEFERRABLE INITIALLY DEFERRED
TABLE "meetings_meeting" CONSTRAINT "meetings_meeting_room_id_02a205a4_fk" FOREIGN KEY (room_id) REFERENCES rooms_room(key) DEFERRABLE INITIALLY DEFERRED
TABLE "recordings_recording" CONSTRAINT "recordings_recording_room_id_799f40af_fk" FOREIGN KEY (room_id) REFERENCES rooms_room(key) DEFERRABLE INITIALLY DEFERRED
TABLE "rooms_room_moderators" CONSTRAINT "rooms_room_moderators_room_id_abd2abc5_fk_rooms_room_key" FOREIGN KEY (room_id) REFERENCES rooms_room(key) DEFERRABLE INITIALLY DEFERRED
TABLE "users_user" CONSTRAINT "users_user_room_id_06ed4152_fk" FOREIGN KEY (room_id) REFERENCES rooms_room(key) DEFERRABLE INITIALLY DEFERRED
【问题讨论】:
您能否显示导致此行为的查询? 你有相关的领域吗? @WillemVanOnsem 请查看我的问题的编辑版本。这是我添加到多对多字段的时候。 @houzayfarifai 请查看我的问题的编辑版本。有一个多对多的字段 你能得到表格的实际描述并提供吗? 【参考方案1】:使用 long varchars 作为主键绝不是一个好主意。 最好使用序列值作为 pk。
但是,既然你想要它,我快速搜索并发现:“一个限制是不能在超过 2,000 个字符的列上创建索引”(找到它here)。
【讨论】:
【参考方案2】:不同的数据库后端对索引列中的字符串长度有不同的限制。
对于postgres,你可以找到限制here(这是一个长度为2000的字符串)
对于mysql,你可以找到限制here [还有一个SO帖子更好地解释它here,这是一个长度为255的字符串)
所以理论上应该没有理由不这样做(Django 还添加了处理数据库可移植性的限制,allowing custom primary_keys, with max_length=255,但您的密钥长度在该范围内)。
我怀疑原因在于您管理数据库的方式,因为我发现您的模型与实际数据库表不匹配(数据库中的键 type
是 varchar(100)
,但模型中的 max_length=50
) .
我建议您查看您的迁移并仔细检查它们,也许重新创建表会起作用,也许那里出了问题。
希望它可能会有所帮助。
【讨论】:
【参考方案3】:不要使用 CharFields 作为主键,最好使用默认的 pk 或 uuid
import uuid
class YourModel(model.Model):
uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)
【讨论】:
【参考方案4】:我认为问题出在type
列/字段上。在 PG 中有 100 个,而您的模型有 50 个 - 作为最大尺寸。
请转至here 使用适合您的方法查看 SQL 查询。一般来说,这类问题来自复杂性。分割,切片,直到你有足够小的一块来解决问题。建议是查看确切的查询 - 这样您就可以查看问题是出在数据库上,还是出在应用程序/模型上。然后你可以尝试更小的模型,或者像两列这样的更小的表 - 键 + 一些东西,没有继承......无论如何 - 我的赌注 - 模型。 :)
【讨论】:
以上是关于Django-Postgres:CharField 的长度作为主键的主要内容,如果未能解决你的问题,请参考以下文章
为啥 django.forms.CharField 中缺少“空白”,但在 django.db.models.CharField 中存在?