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