Django and really big numbers
I ran into a problem in Django that I'd never encountered before this morning: I had a really huge number to store. Tens of billions huge. Postgres and MySQL's integer fields won't store a number that big. They have a field type of bigint, but if you're writing Django models, there's no corresponding bigint field type. There's just an integer.
Turns out, it's really simple to make your own bigint field type. I found out how buried deep in a Trac entry on this. I post it here to help anyone else out who might run into this.
In your models.py, add this:
from django.db.models.fields import IntegerField
from django.conf import settingsclass BigIntegerField(IntegerField):
empty_strings_allowed=False
def get_internal_type(self):
return "BigIntegerField"
def db_type(self):
return 'bigint' # Note this won't work with Oracle.
Then, in your model:
class MyTable(models.Model):
myhugenumber = BigIntegerField()
Note that it's just BigIntegerField(), not model.BigIntegerField() like you're used to doing.
Now, when you syncdb, your myhugenumber field will be a bigint instead of a regular integer field, and you can go on storing a really huge number with glee.
Comments
Ryan Pitts's comment on March 10, 2009 12:24 p.m.
Nice, thanks for sharing this. My guess is that at some point down the road I'll do a Google search and find this again ;)
William M. Hartnett's comment on March 10, 2009 5:51 p.m.
A number in the tens of billions, eh? Sounds like the book is selling well!
Adrian Holovaty's comment on March 11, 2009 12:06 a.m.
In a jiffy, you can also just do an ALTER TABLE and convert it to a bigint directly in your database -- Django wouldn't complain.
The advantage of the technique you posted is that it'll create the column with the proper type if you ever have Django create the table from scratch.

Comments no longer accepted for this entry.
To prevent spam, comments are no longer allowed after 60 days.