dra*_*oot 5 django django-models
我希望模型的主键是未签名的。因此,我这样做:
class MyModel(models.Model):
id = models.PositiveIntegerField(primary_key=True)
Run Code Online (Sandbox Code Playgroud)
这使我UNSIGNED在想要的结果MySQL表中获得一列。但是,我相信我不会在id每次创建新对象时都得到自动分配,是吗?这似乎需要使用AutoField代替。问题是,AutoField已签名。有没有办法创建一个未签名的AutoField?
字段的实际类型在后端指定。在 MySQL 的情况下,后端是django.db.backends.mysql. 此摘录django/db/backends/mysql/creation.py显示了此翻译:
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated MySQL column
# types, as strings. Column-type strings can contain format strings; they'll
# be interpolated against the values of Field.__dict__ before being output.
# If a column type is set to None, it won't be included in the output.
data_types = {
'AutoField': 'integer AUTO_INCREMENT',
'BooleanField': 'bool',
'CharField': 'varchar(%(max_length)s)',
...
Run Code Online (Sandbox Code Playgroud)
要改变这一点,你应该对这个 dict 进行猴子补丁:
from django.db.backends.mysql.creation import DatabaseCreation
DatabaseCreation.data_types['AutoField'] = 'integer UNSIGNED AUTO_INCREMENT'
Run Code Online (Sandbox Code Playgroud)
或者你创建自己的类,这样你就不会弄乱另一个AutoFields:
from django.db.models.fields import AutoField
class UnsignedAutoField(AutoField):
def get_internal_type(self):
return 'UnsignedAutoField'
from django.db.backends.mysql.creation import DatabaseCreation
DatabaseCreation.data_types['UnsignedAutoField'] = 'integer UNSIGNED AUTO_INCREMENT'
Run Code Online (Sandbox Code Playgroud)
然后创建您自己的 PK:
id = UnsignedAutoField()
Run Code Online (Sandbox Code Playgroud)
当它从 下降时AutoField,它将继承其所有行为。
| 归档时间: |
|
| 查看次数: |
1456 次 |
| 最近记录: |