在模型类的关系字段中的SQLAlchemy多表联接

时间:2019-03-20 19:25:41

标签: python sqlalchemy

假设存在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())

我的问题:是否可以通过使用primaryjoinsecondaryjoin的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')

很明显,上面的示例中缺少用户联接,因为我不知道如何正确应用它。

0 个答案:

没有答案