MySQL中有year数据类型,django ORM中没有相应的数据字段类型。我是否可以提供自定义字段类来映射一个特定RDBMS的数据类型?如果是这样,我该怎么做?
答案 0 :(得分:1)
我设法找到满足我需求的以下解决方案(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
然后在模型中使用column数据类型:
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