I can't see anything obviously wrong with what you've written (you said "child.id is None", but I assume you meant child.parent_id). Can you provide a runnable example?
Simon On Thu, Dec 10, 2020 at 8:27 AM Nikola Radovanovic <[email protected]> wrote: > > 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 > > -- > SQLAlchemy - > The Python SQL Toolkit and Object Relational Mapper > > http://www.sqlalchemy.org/ > > To post example code, please provide an MCVE: Minimal, Complete, and > Verifiable Example. See http://stackoverflow.com/help/mcve for a full > description. > --- > You received this message because you are subscribed to the Google Groups > "sqlalchemy" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to [email protected]. > To view this discussion on the web visit > https://groups.google.com/d/msgid/sqlalchemy/4704d9db-2725-416f-9ab4-65077209b8f5n%40googlegroups.com. -- SQLAlchemy - The Python SQL Toolkit and Object Relational Mapper http://www.sqlalchemy.org/ To post example code, please provide an MCVE: Minimal, Complete, and Verifiable Example. See http://stackoverflow.com/help/mcve for a full description. --- You received this message because you are subscribed to the Google Groups "sqlalchemy" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/CAFHwexfBrrXhbRZHg7abuPXL4nYYeVM43zR2CyDL9e5G0NpjGw%40mail.gmail.com.
