python - can't insert into one-to-many relationship in sqlalchemy -
i have 1 many relationship in sqlalchemy don't inserts work properly. have tried make minimal example here:
from sqlalchemy import * sqlalchemy.ext.declarative import declarative_base sqlalchemy.orm import relationship, sessionmaker db = create_engine('sqlite://') db.echo = true metadata = metadata(db) base = declarative_base() session = sessionmaker(bind=db) session = session() class child(base): __table__ = table('child', base.metadata, column('id', integer, primary_key=true), column('parent_id', integer), column('name', string(50)) ) class parent(base): __table__ = table('parent', base.metadata, column('id', integer, primary_key=true), column('name', string(50)) ) children = relationship(child, primaryjoin="parent.id == child.parent_id", foreign_keys=[__table__.c.id]) base.metadata.create_all(db) c = child(id=1, name="c") p = parent(id=1, name="p", children=[c]) session.add(p) session.commit() running gives attributeerror: 'list' object has no attribute '_sa_instance_state' session.add(p).
i tried changing classes this:
class child(base): __tablename__ = 'child' id = column('id', integer, primary_key=true) parent_id = column('parent_id', integer, foreignkey('parent.id')) name = column('name', string(50)) class parent(base): __tablename__ = 'parent' id = column('id', integer, primary_key=true) name = column('name', string(50)) children = relationship(child, backref="parent") and works. specify parent_id foreign key there , use backref syntax. in production code parent table temporary table can't directly reference using foreignkey. whats wrong first code block , how can fixed ?
from sqlalchemy relationship api in docs:
that is, if primaryjoin condition of relationship() a.id == b.a_id, , values in b.a_id required present in a.id, “foreign key” column of relationship() b.a_id.
in example, child.parent_id required present in parent.id. "foreign key" column child.parent_id.
therefore, changing:
foreign_keys=[__table__.c.id] to this:
foreign_keys=[child.__table__.c.parent_id] should solve problem.
Comments
Post a Comment