Hi,
I've been looking around a bit, but can't seem to find any info on this.
We use "before flush/commit" events (but this problem applies to validators as well) to perform a number of things with an istance is persisted.
One of the issues we're facing a lot is when we create a new instance, and set a relation, the foreign key counterpart is still None, and the other way around; If I set the foreign key, the relation is None. Not having the counterpart set, influences how we write the event/validator, as we have to load the counterpart on the fly.
In itself, it's not really an issue, but it's making the code more dense everytime we have to add the code that loads.
I was wondering if there was an easy way to keep the foreign key and relation in sync, when setting one.
A small piece of code to illustrate the issue
class Teacher(Base):
__tablename__ = 'teacher'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
class Student(Base):
__tablename__ = 'student'
id = sa.Column(sa.Integer, primary_key=True)
name = sa.Column(sa.String)
teacher_id = sa.Column(sa.Integer, sa.ForeignKey('teacher.id'))
teacher = relationship('Teacher', backref='students')
teacher1 = Teacher(name='Mark')
teacher2 = Teacher(name='Eugene')
session.add_all((teacher1, teacher2))
session.commit()
student = Student(name='Louis')
student.teacher = teacher1
# assert student.teacher_id == 1 # Wanted behaviour
student.teacher_id = 2
# assert student.teacher == teacher2 # Wanted behaviour
student.teacher = teacher1
# assert student.teacher_id == 1 # Wanted behaviour
I'm able to achieve this behaviour with validators that set it for me, but I don't want to write a validator everytime I have a fk/relation pair, plus I'm not sure this behavious is in the scope of validators.
I've managed to write something dynamic that introspects the class and registers "set" SQLA events, to then set the counterpart, but it's a very elaborate piece of code.
So, in conclusion, is there a built in way to keep the fk/relation of an instance in sync? Or am I going about this the wrong way.
Thanks for your time!
Kind regards,
Maarten