I have an Node
object that should relate to other Node
objects - described by the parents
and children
relationships. I cannot use an association table because I want to store some additional data together with the relation (type of relation, etc).
That way, two nodes can be related to each other with different types of relations. What I want to achieve is to get only unique objects related to each other - meaning that I only care if the nodes are related by at least one relation.
For now, here's my simplified code for the node object. Using association proxy, I can create association objects with additional data using creator
method.
class Node(Base):
__tablename__ = "node"
id = Column(Integer, primary_key=True)
...
children = association_proxy(
"related_children",
"child",
creator=lambda input: Relation(
parent=input.parent,
child=input.child,
type=input.type,
),
)
parents = association_proxy(
"related_parents",
"parent",
creator=lambda input: Relation(
parent=input.parent,
child=input.child,
type=input.type,
),
)
In the Relation
, I have two relationships for both parent and child of the relation.
class Relation(Base):
__tablename__ = "relation"
id = sql.Column(sql.Integer, primary_key=True)
parent_id = sql.Column(sql.Integer, sql.ForeignKey("node.id"))
child_id = sql.Column(sql.Integer, sql.ForeignKey("node.id"))
type = sql.Column(sql.String)
...
parent = relationship(
"Node", foreign_keys=[parent_id], backref=backref("related_children")
)
child = relationship(
"Node", foreign_keys=[child_id], backref=backref("related_parents")
)
The problem is, if I have two nodes, parent and a child, connected by two and more relations, after I get a list of children from the Node.children
, it will return the same child objects as many times as there are relationships between these two nodes.
I know it's just possible to write a custom query with distinct as a property of the Node
, or just convert the return list to set to eliminate the duplicates, but is there a more SQLAlchemy way of doing such case?