Django-Postgres:CharField的长度为主键

时间:2018-06-08 14:11:46

标签: django postgresql django-models

在我的Django模型中,有一个CharField作为主键,其中包含250个字符max_lengthManyToManyField

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

4 个答案:

答案 0 :(得分:3)

不同的数据库后端对索引列中的字符串的长度有不同的限制。

对于postgres,你可以找到限制here(这是一个长度为2000的字符串)

对于mysql,你可以找到限制here [以及更好地解释它的SO帖子here,这是一个长度为255的字符串。

所以理论上应该没有理由不应该这样做(Django也增加了处理数据库可移植性的限制,allowing custom primary_keys, with max_length=255,但你的密钥长度在这个范围内。)

我怀疑原因在于您管理数据库的方式,因为我发现您的模型与实际数据库表之间存在不匹配(数据库中的键typevarchar(100),但是{{1在你的模型中)。

我建议你看看你的迁移并仔细检查它们,也许重新创建表会起作用,也许那里出了问题。

希望它有所帮助。

答案 1 :(得分:1)

使用long varchars作为主键永远不是一个好主意。 将串行值用作pk是一种更好的做法。

但是,既然你想要它,我进行了快速搜索并发现:“一个限制是无法在长度大于2,000个字符的列上创建索引”(找到它here)。

答案 2 :(得分:0)

不要将CharFields用作主键,最好使用默认的pk或uuid

import uuid
class YourModel(model.Model):
    uuid = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)

答案 3 :(得分:0)

我认为问题出在type列/字段。在PG中有100,而你的模型有50 - 最大尺寸。

请使用here使用权限方法来查看SQL查询。一般来说,这种问题来自复杂性。划分,切片直到你有足够小的一块来解决这个问题。建议是查看确切的查询 - 通过这种方式,您可以查看问题是在数据库中,还是在应用程序/模型中。然后你可以尝试更小的模型,或像两列一样的小表 - 键+东西,没有继承...无论如何 - 我的赌注 - 模型。 :)