Sqlalchemy可以使用额外的字段进行多对多的映射

时间:2011-10-12 09:33:16

标签: python orm sqlalchemy pyramid

我和sqlalchemy建立了很多关系:

subject_books = Table('subject_books', Base.metadata,
    Column('subject_id', Integer, ForeignKey('subjects.id')),
    Column('book_id', Integer, ForeignKey('books.id')),
    Column('group', Integer)
)

class Subject(Base):
    __tablename__ = 'subjects'
    id = Column(Integer, primary_key=True)
    value = Column(Unicode(255), unique=True)

class Book(Base):
    __tablename__ = 'books'
    id =  Column(Integer, primary_key=True)
    title = Column(Unicode(255))
    isbn = Column(Unicode(24))
    subjects = relationship('Subject', secondary=subject_books, collection_class=attribute_mapped_collection('group'), backref='books')
之后我创建了一个如下的测试:

book = Book(title='first book',isbn='test')
book.subjects[0] = Subject(value='first subject')
book.subjects[1] = Subject(value='second subject')

session.add(book)
transaction.commit()

它工作正常。但我真正想要的是存储多个具有相同值的主题,所以我尝试了以下测试:

book = Book(title='first book',isbn='test')
book.subjects[0] = [Subject(value='first subject'),Subject(value='second subject')]
book.subjects[1] = [Subject(value='third subject'),Subject(value='forth subject')]

session.add(book)
transaction.commit()

但它不起作用。

可以使用sqlalchemy完成吗?

先谢谢

1 个答案:

答案 0 :(得分:5)

拉​​齐

我认为你正构建错误的关系。

您的关系必须是

预订M2M主题

主题M2M小组

因此,您必须为组创建另一个模型,并且必须在主题

中指定为m2m

你的模特就像。

subject_books = Table('subject_books', Base.metadata,
    Column('subject_id', Integer, ForeignKey('subjects.id')),
    Column('book_id', Integer, ForeignKey('books.id')),        
)
subject_group = Table('subject_groups', Base.metadata,
    Column('group_id', Integer, ForeignKey('groups.id')),
    Column('subject_id', Integer, ForeignKey('subjects.id')),
)

class Subject(Base):
    __tablename__ = 'subjects'
    id = Column(Integer, primary_key=True)
    value = Column(Unicode(255), unique=True)
    groups = relationship('Groups', secondary=subject_groups, backref='subjects')

class Groups(Base):
    __tablename__ = 'groups'
    id = Column(Integer, primary_key=True)
    name = Column(Unicode(255), unique=True)

class Book(Base):
    __tablename__ = 'books'
    id =  Column(Integer, primary_key=True)
    title = Column(Unicode(255))
    isbn = Column(Unicode(24))
    subjects = relationship('Subject', secondary=subject_books, backref='books')

我还查看了attribute_mapped_collection的文档。但每次我发现每个键只与一个对象相关联而不是一个。如果您在任何地方阅读,请提供链接,以便我可以检查它是如何适合您的代码的。

我认为这会对你有所帮助。