<p>灵感来自lfagundes,但有一个小而重要的修正:</p>
<pre><code>class BigAutoField(fields.AutoField):
def db_type(self, connection): # pylint: disable=W0621
if 'mysql' in connection.__class__.__module__:
return 'bigint AUTO_INCREMENT'
return super(BigAutoField, self).db_type(connection)
add_introspection_rules([], [r"^a\.b\.c\.BigAutoField"])
</code></pre>
<p>注意,我不是扩展bigingerfield,而是扩展AutoField。这是一个重要的区别。使用AutoField,Django将从数据库中检索自动递增的id,而biginger则不会。</p>
<p>从bigingerfield更改为AutoField时的一个问题是在AutoField中将数据转换为int。</p>
<p>Django's AutoField的通知:</p>
<pre><code>def to_python(self, value):
if value is None:
return value
try:
return int(value)
except (TypeError, ValueError):
msg = self.error_messages['invalid'] % str(value)
raise exceptions.ValidationError(msg)
</code></pre>
<p>以及</p>
<pre><code>def get_prep_value(self, value):
if value is None:
return None
return int(value)
</code></pre>
<p>事实证明这是可以的,正如在python shell中所验证的那样:</p>
<pre><code>>>> l2 = 99999999999999999999999999999
>>> type(l2)
<type 'long'>
>>> int(l2)
99999999999999999999999999999L
>>> type(l2)
<type 'long'>
>>> type(int(l2))
<type 'long'>
</code></pre>
<p>换句话说,强制转换为int不会截断数字,也不会更改基础类型。</p>