Flask-SQLAlchemy:通过一个关系的多个过滤器 [英] Flask-SQLAlchemy: multiple filters through one relation

查看:190
本文介绍了Flask-SQLAlchemy:通过一个关系的多个过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个模型,标签和照片,有如此多对多的关系:

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

我试图查询所有具有多个特定标签的照片。例如,如果我要用< 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))


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

解决方案

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

这篇关于Flask-SQLAlchemy:通过一个关系的多个过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆