Reputation: 3
In SQLAlchemy, I would like to write a set of records in table A. Then in table B I want to write a record that references an (a priori) unknown number of the records in A.
In python terms, I would create classes A and B and then have a list in B that contains objects of type A.
Can that be done?
Upvotes: 0
Views: 762
Reputation: 1124828
This is not really a SQLAlchemy question, but a basic relational tables question.
You are either talking about a one-to-many relationship, or a many-to-many relationship, both of which SQLAlchemy supports out-of-the-box.
A one-to-many relationship is one of basic containment; a department has many employees, but each employee has only one department. The class with only one outgoing relationship gets the foreign key in this case, so employees refer to departments, not the other way around.
The example from the SQLAlchemy documentation is given as:
class Parent(Base): __tablename__ = 'parent' id = Column(Integer, primary_key=True) children = relationship("Child") class Child(Base): __tablename__ = 'child' id = Column(Integer, primary_key=True) parent_id = Column(Integer, ForeignKey('parent.id'))
So if your A
classes can only be part of one B
set, use this pattern.
A many-to-many relationship is one where both sides can refer to more than one instance of the other side. Think of employees and projects; an employee can be part of multiple projects, and a project can involve multiple employees.
In SQL, this kind of relationship requires an association table, an extra database table that holds the mapping between the two linked types. The SQLAlchemy documentation on many-to-many relationships documents clearly how to do this; here is the example:
association_table = Table('association', Base.metadata, Column('left_id', Integer, ForeignKey('left.id')), Column('right_id', Integer, ForeignKey('right.id')) ) class Parent(Base): __tablename__ = 'left' id = Column(Integer, primary_key=True) children = relationship("Child", secondary=association_table) class Child(Base): __tablename__ = 'right' id = Column(Integer, primary_key=True)
Use this pattern if each A
object can be part of more than one B
set.
Upvotes: 1