Flask-SQLAlchemy:通过一个关系的多个过滤器 [英] Flask-SQLAlchemy: multiple filters through one relation
问题描述
我有两个模型,标签和照片,有如此多对多的关系:
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标记(db.Model):
id = db.Column(db.Integer,primary_key = True)
class图片(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 have two models, Tags and Photos, that have a many-to-many-relationship like so: I am trying to query all photos that have multiple specific tags. For example, if I was to query all photos with In this example, what operation would I need to do in order to get the following result:
Note that you can also check for names:
这篇关于Flask-SQLAlchemy:通过一个关系的多个过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!< Tag 1>
和 < Tag 2> code $:
$ b Photo.query.join(Photo.tags).filter (Tag.id == 1).all()
会返回
[< Photo 1> ;,< ;照片2>,<照片3>,<照片4>]
和
Photo.query .join(Photo.tags).filter(Tag.id == 2).all()
会返回
$ b
[<照片1><照片2> ;]
q =(Photo.query
.filter(Photo.tags.any(Tag.id == 1))
.filter(Photo.tags.any(Tag.id == 2))
)
tag1,tag2 ='tag1','tag2'
q =(Photo.query
.filter(Photo.tags.any(Tag.name == tag1))
.filter(Photo .tags.any(Tag.name == tag2))
)
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')
<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>]
.
[<Photo 1>, <Photo 2>]
q = (Photo.query
.filter(Photo.tags.any(Tag.id == 1))
.filter(Photo.tags.any(Tag.id == 2))
)
tag1, tag2 = 'tag1', 'tag2'
q = (Photo.query
.filter(Photo.tags.any(Tag.name == tag1))
.filter(Photo.tags.any(Tag.name == tag2))
)