I'm using Flask and Peewee to create models for Users
and Appointments
, and each of them have a ForeignKeyField
referencing each other. The problem is, if I define one above the other, Flask will give me x is not defined
.
For example:
class User(Model):
appointments = ForeignKeyField(Appointment, related_name='appointments')
class Appointment(Model):
with_doctor = ForeignKeyField(User, related_name='doctor')
This would return 'User' is not defined
. How am I able to fix this problem?
You generally don't define the foreign key on both sides of the relationship, especially when the relationship isn't a one-to-one.
You should also set the related_name
to something that makes sense on the related model. user.appointments
is probably a better name for accessing a User
's Appointment
s than user.doctor
.
class User(Model):
pass
class Appointment(Model):
with_doctor = ForeignKeyField(User, related_name='appointments')