虽然我没有测试它,但你可能希望只是子类化BigIntegerField
。原本的BigIntegerField
看起来像那样(来源在这里 https://github.com/django/django/blob/ce3351b9508896afdf87d11bd64fd6b5ad928228/django/db/models/fields/__init__.py#L1831):
class BigIntegerField(IntegerField):
empty_strings_allowed = False
description = _("Big (8 byte) integer")
MAX_BIGINT = 9223372036854775807
def get_internal_type(self):
return "BigIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': -BigIntegerField.MAX_BIGINT - 1,
'max_value': BigIntegerField.MAX_BIGINT}
defaults.update(kwargs)
return super(BigIntegerField, self).formfield(**defaults)
Derived PositiveBigIntegerField
可能看起来像这样:
class PositiveBigIntegerField(BigIntegerField):
empty_strings_allowed = False
description = _("Big (8 byte) positive integer")
def db_type(self, connection):
"""
Returns MySQL-specific column data type. Make additional checks
to support other backends.
"""
return 'bigint UNSIGNED'
def formfield(self, **kwargs):
defaults = {'min_value': 0,
'max_value': BigIntegerField.MAX_BIGINT * 2 - 1}
defaults.update(kwargs)
return super(PositiveBigIntegerField, self).formfield(**defaults)
尽管您应该在使用之前对其进行彻底测试。如果你这样做了,请分享结果:)
EDIT:
我错过了一件事——内部数据库表示。这是基于返回的值get_internal_type()
并且存储列类型的定义,例如。here https://github.com/django/django/blob/master/django/db/backends/mysql/creation.py#L20如果是 MySQL 后端并确定here https://github.com/django/django/blob/master/django/db/models/fields/__init__.py#L208。看起来像覆盖db_type()
将使您能够控制字段在数据库中的表示方式。但是,您需要找到一种方法来返回 DBMS 特定的值db_type()
通过检查connection
争论。