Hi,
I have a FK in child pointing to parent table. Also, there is a relationship towards parent from children. I would like to create children and set FK to parent explicitly, without previously loading the parent object. After commit, FK of parent in child table is None. In case I remove relationship from child to parent, FK is set properly.
Here is the simplified code:
class Child(Base):
__tablename__ = 'children'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id', ondelete="CASCADE"), nullable=True)
parent = relationship("Parent", uselist=False) ## <-- when removing this, it works
class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child = Child(parent_id=3)
session.add(child)
session.commit()
# at this moment, child.id is None and not 3., although parent with id ==3 exists in the DB. DB is Postgres 12.
I have tried different loading techniques, but nothing worked.
Can someone please point me into the right direction?
Thank you in advance.
Kindest regards