字段的实际类型在后端指定。在 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)',
...
要改变这一点,您应该对这个 dict 进行猴子修补:
from django.db.backends.mysql.creation import DatabaseCreation
DatabaseCreation.data_types['AutoField'] = 'integer UNSIGNED AUTO_INCREMENT'
或者您创建自己的课程,这样您就不会弄乱其他课程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'
然后创建自己的 PK:
id = UnsignedAutoField()
当它从 下降时AutoField
,它将继承其所有行为。