Woking (it's the tutorial code)
class Son(db.Model):
__tablename__ = 'son'
id = db.Column(db.Integer, primary_key=True)
papa_id = db.Column(db.Integer, db.ForeignKey('
papa.id'))
papa = db.relationship("Papa", foreign_keys=[papa_id], back_populates="son")
class Papa(db.Model):
__tablename__ = 'papa'
id = db.Column(db.Integer, primary_key=True)
son = db.relationship("Son", uselist=False, back_populates="papa")
main:
p1 = Papa()
p2 = Papa()
s1 = Son()
s2 = Son()
db.session.add(p1)
db.session.add(p2)
db.session.add(s1)
db.session.add(s2)
db.session.commit()
p1.son = s1
p2.son = s2
db.session.commit()
p1.son = s2
db.session.commit()
Works like a charm. afterwards every relation is correct
My code (I have to use a super class, that's the only difference):
class Super(db.Model):
__tablename__ = 'super'
id = db.Column(db.Integer, primary_key=True)
class Mama(Super):
__tablename__ = 'mama'
id = db.Column(db.Integer, db.ForeignKey('
super.id'), primary_key=True)
daughter_id = db.Column(db.Integer, db.ForeignKey('
daughter.id'))
daughter = db.relationship("Daughter", foreign_keys=[daughter_id], back_populates="mama")
class Daughter(Super):
__tablename__ = 'daughter'
id = db.Column(db.Integer, db.ForeignKey('
super.id'), primary_key=True)
mama = db.relationship("Mama", foreign_keys=[Mama.daughter_id], uselist=False, back_populates="daughter")
main:
m1 = Mama()
m2 = Mama()
d1 = Daughter()
d2 = Daughter()
db.session.add(m1)
db.session.add(m2)
db.session.add(d1)
db.session.add(d2)
db.session.commit()
m1.daughter = d1
m2.daughter = d2
db.session.commit()
m1.daughter = d2
db.session.commit()
everything is correct EXCEPT:
m2.daughter! it still points on d2 instead of None. And the table contains still the daughter_id of d2.
Thus, what foreign key did I miss?
All the best and stay healthy!
SirAnn