Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can primary key use BigInteger as the AutoField in Django 1.2.4?

Tags:

python

django

It seems that the default primary key is int. Is there anyway to use the big integer for the autofield as the primary key?

like image 676
zs2020 Avatar asked Dec 17 '22 17:12

zs2020


2 Answers

I would suggest you use a newer Django. Official Django documentation doesn't go farther back than 1.3 now. And 1.3 is insecure and unsupported. I realize the question was asked over 3 years ago, but since there is still no accepted answer I will give it a shot.

In Django 1.6.5 you can just do this in your model:

class MyModel(models.Model):
    id = models.BigIntegerField(unique=True, primary_key=True)

The primary_key=True will override the default id on the model. In use this field auto increments with each new model object. It just works!

like image 73
e.thompsy Avatar answered May 08 '23 00:05

e.thompsy


There are a couple of ways I can see to implement this. Either way, you have to define your pk field.

First of all, just create your own id field and override the save method.

modelname(models.Model):
    # model definition

def save(self):
    self.pkfield = nextIntFucntion()
    super(modelname, self).save()

The nextIntFunction() is easy enough with a query of objects ordered by id, then get the id+1

I also found this link BigIntegerField and BigAutoField which seems to solve the problem, but I have not tested it myself

like image 24
neolaser Avatar answered May 08 '23 00:05

neolaser