查看关于Many to Many关系的SQLAlchemy文档 - 它应该完全按照您要查找的内容进行操作。
所以,如果你有型号为User
和Thing
,你可以设置一个二级参数在你们的关系:
from sqlalchemy import Table, Integer, Column, ForeignKey
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
association_table = Table('association', Base.metadata,
Column('user_id', Integer, ForeignKey('user.id')),
Column('thing_id', Integer, ForeignKey('thing.id'))
)
class User(Base):
__tablename__ = 'user'
# Whatever you need in this model
inventory = relationship('Thing', secondary = association_table, backref = 'users')
class Thing(Base):
__tablename__ = 'thing'
# Whatever you need in this model
然后,您可以通过调用访问实例为george
的属于User
Thing
个列表george.inventory
。
希望这会有所帮助。
编辑:重读你的问题,看到你想用backref
- 添加代码来做到这一点。
编辑2:遗漏了一个非常重要的部分。