Flask-SQLAlchemy: multiple filters through one relation

邮差的信 提交于 2019-12-06 02:44:05

问题


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))
     )


来源:https://stackoverflow.com/questions/31306012/flask-sqlalchemy-multiple-filters-through-one-relation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!