Django:构造dyanamic查询 [英] Django: constructing dyanamic query

查看:112
本文介绍了Django:构造dyanamic查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表类型在名称列下具有值Drana,Thriller,Sci-fi等等。另一个表电影
电影表格类型是ManyTomanyField类型表

i have a table Genre having values Drana, Thriller, Sci-fi, etc under "name" column. and another table Movie. In Movie table genre is ManyTOManyField for Genre table

情景

movie_1 = {D,S, T}
movie_2 = {S,T}
movie_3 = {D}
movie_4 = {D, T}

D:戏剧,S:科幻,T:惊悚

D: Drama, S: Sci-Fi, T: Thriller

案例1:
说说用户选择D和T(这是复选框选项)

case 1: Let say user choses D and T (which are checkbox options)

all D movies : movie_1, movie_3, movie_4  ---(a)
all T movies : movie_1, movie_2, movie_4  ---(b)

当用户选择这些选项时:
i想要显示(a)和(b)$ b $的交集的movie_1,movie_2,movie_3,movie_4 b对于上述情况,可以像下列情况一样执行以下查询:

when user selects those options : i want to show movie_1, movie_2, movie_3, movie_4 which is a intersection of both (a) and (b) for above case following query can be done like:

        qs_d = Genre.objects.get(name="Drama")
        qs_t = Genre.objects.get(name="Thriller")
        m_d = Movies.objects.filter( Q(gen__id=qs_d.id) | Q(gen__id=qs_t.id)).distinct()
        for movie_name in m_d:
            print movie_name

在上述查询中,我已经硬编码了戏剧和惊悚片(for解释),但是

根据用户选择的选项数量,我将在{戏剧,喜剧,惊悚片等列表中获得电影类型,在这种情况下构造查询?

in above queries i have hard-coded the genre "Drama" and "Thriller" (for explanation) , but
I'll get the movie genre in a list like {"Drama", "Comedy" , "Thriller"} depending upon the number of options user choses , in that case how can i construct the query ?

推荐答案

| __或__ 函数,或者您可以使用 operator.or _ 函数

所以你可以这样做:

from operator import or_
#Uncomment for Python3
#from functools import reduce
...
qs = [Q(gen__id=Genre.objects.get(name=name).id) for name in names]
m_d = Movies.objects.filter(reduce(or_, qs)).distinct()

应该做你想要的。我不太熟悉Django查询,所以可能会有更好的方法。当然,你可以将它与以下的东西组合起来:

That should do what you're looking for. I'm not terribly familiar with Django queries so there may be a better way. Of course you could combine it with something like:

m_d = Movies.objects.filter(reduce(or_, (Q(gen__id=Genre.objects.get(name=name).id) for name in names))).distinct()

这篇关于Django:构造dyanamic查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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