假设存在3个表或我可以说模型类的情况:
在这种关系中:
User
ManyToMany School
ManyToMany Subject
。
这些多对多关系在关联表中定义如下:
school_user = db.Table('school_user ',
db.Column('user_id', db.Integer, db.ForeignKey('users.id')),
db.Column(school_id', db.Integer, db.ForeignKey('schools.id')))
subject_school = db.Table('subject_school ',
db.Column('school_id', db.Integer, db.ForeignKey('schools.id')),
db.Column('subject_id', db.Integer, db.ForeignKey('subjects.id')))
class User(db.Model):
schools= db.relationship('School', secondary=school_user , backref=db.backref('users', lazy='dynamic'))
class Subject(db.Model):
schools= db.relationship('School',
secondary=subject_school,
backref=db.backref('subjects',
lazy='dynamic'))
我想查询Subjects
所属的属于Schools
的所有User
。
我可以通过以下方式轻松实现它:
class User:
@property
def subjects(self):
return (Subject
.query
.join(School, Subject.schools)
.join(User, School.users)
.filter(User.id == self.id)
.all())
我的问题:是否可以通过使用primaryjoin
和secondaryjoin
的SQLAlchemy关系字段来实现?类似的东西(出于演示目的,不起作用):
class User:
subjects = db.relationship('Subject',
secondary=subject_school,
secondaryjoin='School.id==subject_school.c.school_id',
primaryjoin='Subject.id==subject_school.c.subject_id')
很明显,上面的示例中缺少用户联接,因为我不知道如何正确应用它。