SQLAlchemy, one to many vs many to one
Posted
by sadvaw
on Stack Overflow
See other posts from Stack Overflow
or by sadvaw
Published on 2010-04-12T09:55:24Z
Indexed on
2010/04/12
14:02 UTC
Read the original article
Hit count: 221
sqlalchemy
Dear Everyone,
I have the following data:
CREATE TABLE `groups` (
`bookID` INT NOT NULL,
`groupID` INT NOT NULL,
PRIMARY KEY(`bookID`),
KEY( `groupID`)
);
and a book table which basically has books( bookID, name, ... ), but WITHOUT groupID. There is no way for me to determine what the groupID is at the time of the insert for books.
I want to do this in sqlalchemy. Hence I tried mapping Book to the books joined with groups on book.bookID=groups.bookID.
I made the following:
tb_groups = Table( 'groups', metadata,
Column('bookID', Integer, ForeignKey('books.bookID'), primary_key=True ),
Column('groupID', Integer),
)
tb_books = Table( 'books', metadata,
Column('bookID', Integer, primary_key=True),
tb_joinedBookGroup = sql.join( tb_books, tb_groups, \
tb_books.c.bookID == tb_groups.c.bookID)
and defined the following mapper:
mapper( Group, tb_groups, properties={
'books': relation(Book, backref='group')
})
mapper( Book, tb_joinedBookGroup )
...
However, when I execute this piece of code, I realized that each book object has a field groups, which is a list, and each group object has books field which is a singular assigment. I think my definition here must have been causing sqlalchemy to be confused about the many-to-one vs one-to-many relationship.
Can someone help me sort this out?
My desired goal is g.books = [b, b, b, .. ] book.group = g,
where g is an instance of group, and b is an instance of book
© Stack Overflow or respective owner