django ORM 自定义字段

 1 class FixedCharField(models.Field):
 2     """
 3     自定义的char类型的字段类
 4     """
 5     def __init__(self, max_length, *args, **kwargs):
 6         self.max_length = max_length
 7         super(FixedCharField, self).__init__(max_length=max_length, *args, **kwargs)
 8 
 9     def db_type(self, connection):
10         """
11         限定生成数据库表的字段类型为char,长度为max_length指定的值
12         """
13         return 'char(%s)' % self.max_length
14 
15 
16 class Class(models.Model):
17     id = models.AutoField(primary_key=True)
18     title = models.CharField(max_length=25)
19     # 使用自定义的char类型的字段
20     cname = FixedCharField(max_length=25)
原文地址:https://www.cnblogs.com/linkenpark/p/10922884.html