There is a year data type in MySQL and there is no corresponding data field type in django ORM. Can I provide a custom field class to map data type for one specific RDBMS? If so, how can I do that?
MySQL中有一年的数据类型,django ORM中没有相应的数据字段类型。我是否可以提供自定义字段类来映射一个特定RDBMS的数据类型?如果是这样,我该怎么办?
1 个解决方案
#1
1
I managed to find following solution which satisfies my needs (models.py
):
我设法找到满足我需求的以下解决方案(models.py):
from django.core.exceptions import FieldError
class YearField(models.Field):
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
return 'year'
else:
raise FieldError
and then use the column datatype in models:
然后在模型中使用列数据类型:
class Band(models.Model):
"""Music band"""
class Meta:
db_table = 'band'
name = models.CharField(max_length=64)
active_since = YearField()
active_until = YearField(null=True)
genres = models.ManyToManyField(Genre)
def __unicode__(self):
return self.name
#1
1
I managed to find following solution which satisfies my needs (models.py
):
我设法找到满足我需求的以下解决方案(models.py):
from django.core.exceptions import FieldError
class YearField(models.Field):
def db_type(self, connection):
if connection.settings_dict['ENGINE'] == 'django.db.backends.mysql':
return 'year'
else:
raise FieldError
and then use the column datatype in models:
然后在模型中使用列数据类型:
class Band(models.Model):
"""Music band"""
class Meta:
db_table = 'band'
name = models.CharField(max_length=64)
active_since = YearField()
active_until = YearField(null=True)
genres = models.ManyToManyField(Genre)
def __unicode__(self):
return self.name