Django: constructing dyanamic query -


i have table genre having values drana, thriller, sci-fi, etc under "name" column. , table movie. in movie table genre manytomanyfield genre table

scenario

movie_1 = {d,s, t} movie_2 = {s,t} movie_3 = {d} movie_4 = {d, t} 

d: drama, s: sci-fi, t: thriller

case 1: let user choses d , t (which checkbox options)

all d movies : movie_1, movie_3, movie_4  ---(a) t movies : movie_1, movie_2, movie_4  ---(b) 

when user selects options : want show movie_1, movie_2, movie_3, movie_4 intersection of both (a) , (b) above case following query can 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()         movie_name in m_d:             print movie_name 

in above queries have hard-coded genre "drama" , "thriller" (for explanation) , but
i'll movie genre in list {"drama", "comedy" , "thriller"} depending upon number of options user choses , in case how can construct query ?

| __or__ function, or can use operator.or_ function.

so this:

from operator import or_ #uncomment python3 #from functools import reduce ... qs = [q(gen__id=genre.objects.get(name=name).id) name in names] m_d = movies.objects.filter(reduce(or_, qs)).distinct() 

that should you're looking for. i'm not terribly familiar django queries there may better way. of course combine like:

m_d = movies.objects.filter(reduce(or_, (q(gen__id=genre.objects.get(name=name).id) name in names))).distinct() 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

.htaccess - Matching full URL in RewriteCond -