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, add this:

from django.db.models.fields import IntegerField
from django.conf import settings

class BigIntegerField(IntegerField):
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.

By: Matt Waite | Posted: March 10, 2009 | Tags: Django | 3 comments