Model Definitions

To begin working with the data, we’ll define the model classes that correspond to the tables in the diagram.

Note

In some cases we explicitly specify column names for a particular field. This is so our models are compatible with the database schema used for the postgres exercises.

  1. from functools import partial
  2. from peewee import *
  3. db = PostgresqlDatabase('peewee_test')
  4. class BaseModel(Model):
  5. class Meta:
  6. database = db
  7. class Member(BaseModel):
  8. memid = AutoField() # Auto-incrementing primary key.
  9. surname = CharField()
  10. firstname = CharField()
  11. address = CharField(max_length=300)
  12. zipcode = IntegerField()
  13. telephone = CharField()
  14. recommendedby = ForeignKeyField('self', backref='recommended',
  15. column_name='recommendedby', null=True)
  16. joindate = DateTimeField()
  17. class Meta:
  18. table_name = 'members'
  19. # Conveniently declare decimal fields suitable for storing currency.
  20. MoneyField = partial(DecimalField, decimal_places=2)
  21. class Facility(BaseModel):
  22. facid = AutoField()
  23. name = CharField()
  24. membercost = MoneyField()
  25. guestcost = MoneyField()
  26. initialoutlay = MoneyField()
  27. monthlymaintenance = MoneyField()
  28. class Meta:
  29. table_name = 'facilities'
  30. class Booking(BaseModel):
  31. bookid = AutoField()
  32. facility = ForeignKeyField(Facility, column_name='facid')
  33. member = ForeignKeyField(Member, column_name='memid')
  34. starttime = DateTimeField()
  35. slots = IntegerField()
  36. class Meta:
  37. table_name = 'bookings'