简体   繁体   中英

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. 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 . 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.

So how can I store static Gender data in the database, then query the Person table by the enum values?

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. 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM