Flask-SQLAlchemy: multiple filters through one rel

2020-07-16 06:59发布

问题:

I have two models, Tags and Photos, that have a many-to-many-relationship like so:

tag_identifier = db.Table('tag_identifier',
                          db.Column('photo_id', db.Integer, db.ForeignKey('photo.id')),
                          db.Column('tag_id', db.Integer, db.ForeignKey('tag.id'))
                         )

class Tag(db.Model):
  id = db.Column(db.Integer, primary_key=True)

class Photo(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  tags = db.relationship('Tag', secondary=tag_identifier,
                         backref=db.backref('photos', lazy='dynamic'), lazy='dynamic')

I am trying to query all photos that have multiple specific tags. For example, if I was to query all photos with <Tag 1> and <Tag 2>:


Photo.query.join(Photo.tags).filter(Tag.id==1).all() would return

[<Photo 1>, <Photo 2>, <Photo 3>, <Photo 4>], and

Photo.query.join(Photo.tags).filter(Tag.id==2).all() would return

[<Photo 1>, <Photo 2>, <Photo 5>, <Photo 6>].


In this example, what operation would I need to do in order to get the following result: [<Photo 1>, <Photo 2>]

回答1:

q = (Photo.query
     .filter(Photo.tags.any(Tag.id == 1))
     .filter(Photo.tags.any(Tag.id == 2))
     )

Note that you can also check for names:

tag1, tag2 = 'tag1', 'tag2'
q = (Photo.query
     .filter(Photo.tags.any(Tag.name == tag1))
     .filter(Photo.tags.any(Tag.name == tag2))
     )