1
Class Bed
   id
Class Guest
    id
    bed_assignments = relationship(

          primaryjoin=(
              "and_(Guest.id"
              "==foreign(BedAssignment.guest_id),"
              "BedAssignment.bed_status=='occupied')"
         ),

)

Class BedAssignment
    FK Guest
    FK Bed

each class is in a file and referencing Guest in BedAssignment class for the FK purpose next to referencing BedAssignment for relationship purpose creates a cross reference.

I tried using text version of FK or relationship referencing , similar to: Column(Integer, ForeignKey("bed.id") But it seems like a workaround as it stops alembic scripts generation that errors looking for reference.

How the cross reference be solved in this case of relationship model?

Azuz
  • 31
  • 6

1 Answers1

0

Since your relationship is from an association table + has secondary join specifications, construct your relationship as follows:

bed_assignments = relationship(
    "Bed", #class name of the table
    secondary = "BedAssignment", #table name of the association table
    # Consider using exact tablenames for your join statement...
    primaryjoin = """and_(
        Guest.id==BedAssignment.guest_id,
        BedAssignment.bed_status=='occupied'
    )""",
    backref=backref("Bed", lazy="dynamic"), # if you want the relationship to be observable on the other class... (Guests as children of Beds)
    lazy='dynamic', #only load as needed
    post_update=True, # this allows updating of dependent rows without collisions or cyclical dependencies 
    )
Yaakov Bressler
  • 9,056
  • 2
  • 45
  • 69
  • 1
    Thanks Yaakov! I needed to reference BedAssignment in guest and vice versa for interpretting relationship classes. I was missing the fact that I could reference classes in the _init_.py in models folder which makes my question answered in other threads. – Azuz Dec 17 '20 at 21:50
  • Glad to hear it. Also, `backref` would only require the relationship to be declared once. @Azuz – Yaakov Bressler Dec 17 '20 at 22:14
  • Also, consider accepting this answer if it solves your Q – Yaakov Bressler Dec 17 '20 at 22:15