1

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?

Paul R
  • 208,748
  • 37
  • 389
  • 560
josh
  • 75
  • 1
  • 8

3 Answers3

2

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 Appointments than user.doctor.

class User(Model):
   pass

class Appointment(Model):
   with_doctor = ForeignKeyField(User, related_name='appointments')
dirn
  • 19,454
  • 5
  • 69
  • 74
0

You can define it as a string as far as i know:

class User(Model):
   appointments = ForeignKeyField("Appointment", related_name='appointments')

class Appointment(Model):
   with_doctor = ForeignKeyField(User, related_name='doctor')

if the declaration is before the creation, you have the option to write it as a string.

I'm not sure, i think that the bind is at runtime.

omri_saadon
  • 10,193
  • 7
  • 33
  • 58
0

try some changes like this, an example for Names & Addresses :

class Person(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    addresses = db.relationship('Address', backref='person', lazy='dynamic')

class Address(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    person_id = db.Column(db.Integer, db.ForeignKey('person.id'))

as far as i know, you should use db.ForeignKey() for a relationship like this ... ForeignKeyField() defined in django

Arash Hatami
  • 5,297
  • 5
  • 39
  • 59