'Conditional backref in SQL alchemy (take field from either grandparent or parent)
Let's say I have the following relationships:
GrandParent with id
Parent with grand_parent_id
Child with grand_parent_id and parent_id
I want the Child to inherit the grand_parent_id from either Parent or GrandParent, depending on how it's created.
When I try to run the following:
session.add(
GrandParent(
Parent(
Child()
)
)
)
GrandParent will receive id 1, Parent will get grand_parent_id=1, but the child will receive grand_parent_id=None, even though it does receive the correct parent_id=1. Currently, for the Child, the backref (back_populates) is set to grand_parents.id column.
How could I have the Child inherit the grandparent id? What should my ORM models look like? Or should I just change the design entirely?
Currently the constraint that is forcing me to have this is that the Child can be created with either both GrandParent and Parent or just the GrandParent. GrandParent can also be a Parent, so maybe there's a different way to describe this type of relationship.
Any ideas are welcome!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
