我与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完成吗?
提前谢谢

最佳答案

拉济
我认为你在建立错误的关系。
你的关系一定是
预订M2M主题
主题M2M组
因此,您必须为group再创建一个模型,该模型必须在Subject中指定为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的文档。但每次我发现每个键只与一个对象关联,而不是与多个对象关联。如果你在任何地方阅读,请提供链接,以便我可以检查它将如何适合你的代码。
我想这对你有帮助。

09-25 20:22