class Parent(Base):
__tablename__ = "parent"
id = Column(Integer, primary_key=True)
oldest_child_id = Column(Integer, ForeignKey("child.id"))
oldest_child = relationship("Child", foreign_keys=oldest_child_id)
youngest_child_id = Column(Integer, ForeignKey("child.id"))
youngest_child = relationship("Child", foreign_keys=oldest_child_id)
# children = ...
class Child(Base):
__tablename__ = "child"
id = Column(Integer, primary_key=True)
@property
def children(self):
return [self.oldest_child, self.youngest_child] # Or set(), or tuple().
children = relationship("Child")
children = relationship("Child", back_populates="parent")
The line you commented out from the example was either:children = relationship("Child")children = relationship("Child", back_populates="parent")both of those lines create an iterable list of all the Child objects on the `children`
sqlalchemy.exc.AmbiguousForeignKeysError: Could not determine join condition between parent/child tables on relationship Parent.children - there are multiple foreign key paths linking the tables. Specify the 'foreign_keys' argument, providing a list of those columns which should be counted as containing a foreign key reference to the parent table.
children = relationship("Child", foreign_keys=[oldest_child_id, youngest_child_id])
Off the top of my head, the simplest way to accomplish this would be to add a "parent_id" column on the child table, and then create a relationship for "children" that correlates the `Parent.id` to `Child.parent_id`.
That change might not work with your data model if a Child can have multiple parents.
Indeed, Child does have multiple parents…
Ok, so this isn't a one-to-one relationship, but a many-to-many relationship.
children = [youngest_child, oldest_child]
@property def children(self): children = (getattr(self, r.key) for r in self.__mapper__.relationships if r.target.name == "child") return [c for c in children if c is not None]
sqlalchemy.ext.declarative
extension will also have its mapper available via the __mapper__
attribute.from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base(metadata=MetaData(naming_convention={...}))
class Parent(Base):
...
class Child(Base):
...
If I understand you correctly, then the solution above is as good as it gets and SQLA doesn’t provide a builtin solution for what I’m trying to do?