Last active
July 4, 2019 05:39
-
-
Save pinfort/8d3433d304b105909ed4da73e366eee3 to your computer and use it in GitHub Desktop.
Django database fields for using unsigned bigint column
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 import models | |
class PositiveBigIntergerRelDbTypeMixin(models.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 = _("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
このままだとget_internal_type()がエラーになってしまうのでやっぱりdb_type()関数も書かないといけないね