Last active
December 21, 2019 00:29
-
-
Save nmfzone/260058356c187dd6582e36fd1801aab6 to your computer and use it in GitHub Desktop.
PositiveBigAutoFileld & PositiveBigIntegerField. Auto Increment Big Integer in Django (mysql)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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, | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
<-- hereThen, you can use it like so: