SQLAlchemy ORM one-to-many relationship is not loading all records from DB
Using the SqlAlchemy ORM, I've been trying to setup a one-to-many relationship between a parent table that has "child" records in a child table. The table and mapper declarations are below. The problem is, only one child record is read from the DB into the "children" attribute when there should be many records.
child_table = Table('child_table', metadata_obj,
Column('field_1', Integer, ForeignKey('parent_table.field_1'),
primary_key=True),
Column('field_2开发者_如何学运维', String, ForeignKey('parent_table.field_2'),
primary_key=True),
autoload=True
mapper(Parent_Class, parent_table, properties={
'children': relation(Child_Class, lazy=False, # Eager load
primaryjoin=and_(child_table.c.field_1==parent_table.c.field_1,
parent_table.c.field_2==parent_table.c.field_2),
backref="parents"),
})
The problem was in the child_table definition. I had only defined the fields with a foreign key relationship as being part of the primary key for the child_table. However, those fields (field_1 & field_2) weren't the complete primary key. So, it appears that SQLAlchemy was only loading one row. I added field_3 and field_4 to fully define the primary key for the child_table and then SQLAlchemy successfully read all records.
child_table = Table('child_table', metadata_obj,
Column('field_1', Integer, ForeignKey('parent_table.field_1'),
primary_key=True),
Column('field_2', String, ForeignKey('parent_table.field_2'),
primary_key=True),
Column('field_3', String, primary_key=True),
Column('field_4', String, primary_key=True),
autoload=True
精彩评论