Model Definitions

To begin working with the data, we’ll define the model classes that correspondto 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 thepostgres exercises.

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