Skip to content

Instantly share code, notes, and snippets.

@nmfzone
Last active December 21, 2019 00:29
Show Gist options
  • Save nmfzone/260058356c187dd6582e36fd1801aab6 to your computer and use it in GitHub Desktop.
Save nmfzone/260058356c187dd6582e36fd1801aab6 to your computer and use it in GitHub Desktop.
PositiveBigAutoFileld & PositiveBigIntegerField. Auto Increment Big Integer in Django (mysql)
from django.db.models import fields
__all__ = [
'PositiveBigAutoField', 'PositiveBigIntegerField',
]
class PositiveBigAutoField(fields.AutoField):
def db_type(self, connection):
if 'mysql' in connection.__class__.__module__:
return 'bigint unsigned AUTO_INCREMENT'
return super().db_type(connection)
def rel_db_type(self, connection):
return PositiveBigIntegerField().db_type(connection=connection)
class PositiveBigIntegerField(fields.BigIntegerField):
def db_type(self, connection):
if 'mysql' in connection.__class__.__module__:
return 'bigint unsigned'
return super().db_type(connection)
def db_check(self, connection):
data = self.db_type_parameters(connection)
if 'oracle' in connection.__class__.__module__:
return '%(qn_column)s >= 0' % data
elif 'postgresql' in connection.__class__.__module__:
return '"%(column)s" >= 0' % data
elif 'sqlite3' in connection.__class__.__module__:
return '"%(column)s" >= 0' % data
return super().db_check(connection)
def formfield(self, **kwargs):
return super().formfield(**{
'min_value': 0,
**kwargs,
})
@nmfzone
Copy link
Author

nmfzone commented Dec 20, 2019

You can put that code anywhere, but for me ideally I would like to put that in:

---- app
-------- __init__.py
-------- db
------------ __init__.py
------------ models
---------------- __init__.py
---------------- fields
-------------------- __init__.py <-- here

Then, you can use it like so:

from .db.models import fields as common_fields
from django.db import models
from django.contrib.auth.models import AbstractBaseUser

class User(AbstractBaseUser):
    id = common_fields.PositiveBigAutoField(
        auto_created=True,
        primary_key=True,
        serialize=False,
        verbose_name='ID'
    )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment