[英]Static table in peewee
I want to store an enum in the database, according to this . 我想存储在数据库中的枚举,根据这个 。
So let's say, I have a Gender enum and a Person model. 假设我们有一个Gender枚举和一个Person模型。 I want to do a select like
Person.select().where(Person.gender == Gender.MALE)
This can be achieved by creating a GenderField in Person as described here . 我想要做一个选择像
Person.select().where(Person.gender == Gender.MALE)
这可以通过所描述的人创造一个GenderField来实现此 。 But the gender won't be in the database as a table, and I want the Person to have foreign keys to the Gender table. 但是性别不会以表格形式出现在数据库中,我希望此人对Gender表格具有外键。
So how can I store static Gender data in the database, then query the Person table by the enum values? 那么如何将静态Gender数据存储在数据库中,然后通过枚举值查询Person表?
You can, as part of the table creation process, populate the gender table: 在表创建过程中,您可以填充性别表:
class Gender(Model):
label = CharField(primary_key=True)
class Meta:
database = db
def create_schema():
# Use an execution context to ensure the connection is closed when
# we're finished.
with db.execution_context():
db.create_tables([Gender, ...], True)
if not Gender.select().exists():
defaults = ['MALE', 'FEMALE', 'UNSPECIFIED']
Gender.insert_many([{'label': label} for label in defaults]).execute()
The only reason to make Gender a table in this example, though, would be if you plan to dynamically add new Gender labels at run-time. 但是,在此示例中使Gender成为表格的唯一原因是,如果您计划在运行时动态添加新的Gender标签。 If the set of values is fixed, my opinion is you're better off doing something like this:
如果值的集合是固定的,那么我认为您最好这样做:
class Person(Model):
GENDER_MALE = 'M'
GENDER_FEMALE = 'F'
GENDER_UNSPECIFIED = 'U'
name = CharField()
gender = CharField()
# Then, simply:
Person.create(name='Huey', gender=Person.GENDER_MALE)
Person.create(name='Zaizee', gender=Person.GENDER_UNSPECIFIED)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.