且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Django BigInteger自动增量字段为主键?

更新时间:2023-02-12 08:32:58


注意:根据Larry的代码,这个答案被修改了。以前的解决方案扩展fields.BigIntegerField,但更好地扩展fields.AutoField


我有同样的问题,并解决了以下代码:来自django.db.models导入字段的

 
来自south.modelsinspector import add_introspection_rules

class BigAutoField (fields.AutoField):
def db_type(self,connection):
if'mysql'in connection .__ class __.__ module__:
return'bigint AUTO_INCREMENT'
return super(BigAutoField ,self).db_type(connection)

add_introspection_rules([],[^ MYAPP\.fields\.BigAutoField])

显然这对南迁很有效。


I'm currently building a project which involves a lot of collective intelligence. Every user visiting the web site gets created a unique profile and their data is later used to calculate best matches for themselves and other users.

By default, Django creates an INT(11) id field to handle models primary keys. I'm concerned with this being overflown very quickly (i.e. ~2.4b devices visiting the page without prior cookie set up). How can I change it to be represented as BIGINT in MySQL and long() inside Django itself?

I've found I could do the following (http://docs.djangoproject.com/en/dev/ref/models/fields/#bigintegerfield):

class MyProfile(models.Model):
    id = BigIntegerField(primary_key=True)

But is there a way to make it autoincrement, like usual id fields? Additionally, can I make it unsigned so that I get more space to fill in?

Thanks!

NOTE: This answer as modified, according to Larry's code. Previous solution extended fields.BigIntegerField, but better to extend fields.AutoField

I had the same problem and solved with following code:

from django.db.models import fields
from south.modelsinspector import add_introspection_rules

class BigAutoField(fields.AutoField):
    def db_type(self, connection):
        if 'mysql' in connection.__class__.__module__:
            return 'bigint AUTO_INCREMENT'
        return super(BigAutoField, self).db_type(connection)

add_introspection_rules([], ["^MYAPP\.fields\.BigAutoField"])

Apparently this is working fine with south migrations.