Setting the FK not performed when relationship is declared

10 views
Skip to first unread message

Nikola Radovanovic

unread,
Dec 10, 2020, 3:27:17 AM12/10/20
to sqlalchemy
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

Simon King

unread,
Dec 10, 2020, 5:00:40 AM12/10/20
to sqlal...@googlegroups.com
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
> --
> 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 sqlalchemy+...@googlegroups.com.
> To view this discussion on the web visit https://groups.google.com/d/msgid/sqlalchemy/4704d9db-2725-416f-9ab4-65077209b8f5n%40googlegroups.com.

Nikola Radovanovic

unread,
Dec 10, 2020, 7:08:44 AM12/10/20
to sqlalchemy
Yes, my bad; it should state: # at this moment, child.parent_id is None. What is strange, when added single_parent=True to the relationship - it then worked as I would expected. I guess its some of my misunderstanding of how relationship works. In case needed, I will set working sample, this one was just extracted from more complicated code.

Thanks!

Reply all
Reply to author
Forward
0 new messages