peewee中创建自己的Field
Posted 迷阳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了peewee中创建自己的Field相关的知识,希望对你有一定的参考价值。
peewee中创建自己的Field,主要通过继承Field或其子类来完成,
- 如果有mysql中对应的字段,则将其赋值给db_field即可。这里对set, enum并没有找到通用的字段定义,但是对具体的业务可以进行如GenderField这样的个性化定制。
- 如果没有,则使用其父类的db_field字段,并定义db_value和python_value两个方法来完成与数据库中数据类型之间的转化
1 # 时间戳字段
2 class TimeStampField(Field):
3 db_field = ‘timestamp‘
4
5 class SmallIntegerField(IntegerField):
6 db_field = ‘smallint‘
7
8 class PasswordField(FixedCharField):
9
10 def __init__(self, *args, **kwargs):
11 self.max_length =64
12 super(PasswordField, self).__init__(max_length=self.max_length, *args, **kwargs)
13
14 def db_value(self, value):
15 return encrypt(value)
16
17 def python_value(self, value):
18 return encrypt(value)
19 # 性别字段
20 class GenderField(Field):
21 db_field = ‘enum("f", "m")‘
3 db_field = ‘timestamp‘
4
5 class SmallIntegerField(IntegerField):
6 db_field = ‘smallint‘
7
8 class PasswordField(FixedCharField):
9
10 def __init__(self, *args, **kwargs):
11 self.max_length =64
12 super(PasswordField, self).__init__(max_length=self.max_length, *args, **kwargs)
13
14 def db_value(self, value):
15 return encrypt(value)
16
17 def python_value(self, value):
18 return encrypt(value)
19 # 性别字段
20 class GenderField(Field):
21 db_field = ‘enum("f", "m")‘
建立表格如下:
1 class Base(Model):
2 class Meta:
3 database = db
4
5 class Person(Base):
6 name = CharField(max_length=20, default=‘haha‘)
7 intro = TextField(default=‘‘)
8 birth = DateTimeField(default=datetime.now())
9 Married = BooleanField(default=False)
10 height = FloatField(default=0)
11 wight = DoubleField(default=0)
12 salary = DecimalField(default=0)
13 Save = BigIntegerField(default=0)
14 family = SmallIntegerField(default=0)
15 age = IntegerField(default=0)
16 username = CharField(max_length=20)
17 password = PasswordField(default=‘‘)
18 ctime = TimeStampField()
19 today = DateField(default=datetime.date(datetime.today()))
20 now = TimeField(default=datetime.today())
21 secret = BlobField(default=‘‘)
22 gender = GenderField()
3 database = db
4
5 class Person(Base):
6 name = CharField(max_length=20, default=‘haha‘)
7 intro = TextField(default=‘‘)
8 birth = DateTimeField(default=datetime.now())
9 Married = BooleanField(default=False)
10 height = FloatField(default=0)
11 wight = DoubleField(default=0)
12 salary = DecimalField(default=0)
13 Save = BigIntegerField(default=0)
14 family = SmallIntegerField(default=0)
15 age = IntegerField(default=0)
16 username = CharField(max_length=20)
17 password = PasswordField(default=‘‘)
18 ctime = TimeStampField()
19 today = DateField(default=datetime.date(datetime.today()))
20 now = TimeField(default=datetime.today())
21 secret = BlobField(default=‘‘)
22 gender = GenderField()
mysql中的表描述如下:
以上是关于peewee中创建自己的Field的主要内容,如果未能解决你的问题,请参考以下文章
peewee.InterfaceError:保存大量数据时绑定参数错误