Skip to content

Instantly share code, notes, and snippets.

@mozillalives
Forked from pinfort/Django_unsignedBigint.py
Last active May 18, 2018 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mozillalives/56e8b2cf87396c2cc5754d570d52e79a to your computer and use it in GitHub Desktop.
Save mozillalives/56e8b2cf87396c2cc5754d570d52e79a to your computer and use it in GitHub Desktop.
Django database fields for using unsigned bigint column
from django.db import models
from django.utils.translation import ugettext
class PositiveBigIntegerRelDbTypeMixin(models.fields.PositiveIntegerRelDbTypeMixin):
def rel_db_type(self, connection):
if connection.features.related_fields_match_type:
return self.db_type(connection)
else:
return models.BigIntegerField().db_type(connection=connection)
class PositiveBigIntegerField(PositiveBigIntegerRelDbTypeMixin, models.BigIntegerField):
description = ugettext("Positive big integer")
def get_internal_type(self):
return "PositiveBigIntegerField"
def formfield(self, **kwargs):
defaults = {'min_value': 0}
defaults.update(kwargs)
return super().formfield(**defaults)
def db_type(self, connection):
# get db vendor ex.mysql, postgresql, sqlite...
db_vendor = connection.vendor
if db_vendor == "mysql":
return "bigint UNSIGNED"
elif db_vendor == "oracle":
return "NUMBER(20)"
elif db_vendor == "postgresql":
# postgresql is not supported 'unsigned'
return "bigint"
elif db_vendor == "sqlite":
return "bigint unsigned"
else:
# if db_vendor is unknown(BaseDatabaseWrapper), we should return None
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment