Skip to content

Instantly share code, notes, and snippets.

@novaleksey
Last active January 30, 2022 20:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save novaleksey/187e43660c4e2e56f7b972cf982751e1 to your computer and use it in GitHub Desktop.
Save novaleksey/187e43660c4e2e56f7b972cf982751e1 to your computer and use it in GitHub Desktop.
Peewee 3 Enum Field Postgres
from peewee import *
database = PostgresqlDatabase(
'my_database',
**{'user': 'postgres', 'password': 'postgres', 'host': 'localhost', 'port': 5432, 'autorollback': True}
)
class BaseModel(Model):
class Meta:
database = database
@classmethod
def create_table(cls, *args, **kwargs):
for field in cls._meta.fields.values():
if hasattr(field, "pre_field_create"):
field.pre_field_create(cls)
cls._schema.create_table()
class EnumField(Field):
def pre_field_create(self, model):
field = "e_%s" % self.name
self.model._meta.database.execute_sql(
"DROP TABLE IF EXISTS %s;" % self.model._meta.table_name
)
self.model._meta.database.execute_sql(
"DROP TYPE IF EXISTS %s;" % field
)
tail = ', '.join(["'%s'"] * len(self.choices)) % tuple(self.choices)
q = "CREATE TYPE %s AS ENUM (%s);" % (field, tail)
self.model._meta.database.execute_sql(q)
self.field_type = "e_%s" % self.name
class MyTable(BaseModel):
type = EnumField(choices=['one', 'two', 'three'])
class Meta:
table_name = 'my_table'
database.connect()
database.create_tables([MyTable])
MyTable.create(type='two')
MyTable.get(id=1).type #two
database.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment