Django ANDing queryset filters using variable assignment -


let's have queryset of products has tons of prefetch objects in it. among prefetch objects "categories", , categories can have "filters". not every product has categories , filters defined.

example categories "price" , "color", , filters "lt $5" , "blue".

i can products have "price" , "color" defined enough, using exclude.

but how this, example:

all products have "price"=* defined, , products have "color"="blue" defined.

any ideas?

edit: i'm gonna go ahead , show solution came with. bear in mind example above simplified. there dozens of categories, each dozens of filters.

imagine the user chose category 'shoes' not filters 'shoes': 'women' or 'shoes': 'football'.

and chose category 'price' , filter 'price': 'lt $5'

from django.db.models import q import operator argument_list = [] # categories_selected = categories have been checked on page      c in categories_selected:  # categories_filtered = (selected) categories have filters applied     if c not in categories_filtered:         # here <category>_id defined         argument_list.append(q(**{c+'__id__isnull': false}))     else:         f in get_category_filters_from_url(filters_selected, c):         # get_category_filters_from_url() returns filters (by id) belonging          # given category, e.g., 'price': 'lt $5'             argument_list.append(q(**{c+'__id': f}))  resources = resources.filter(reduce(operator.or_, argument_list)).distinct() 

i hope that's clear enough, , helps else muddle through this.

without knowing how models like, i'd use following query:

query and:

product.objects.filter(categories__price__isnull=false, categories__color='blue') 

query or:

from django.db.models import q  product.objects.filter(q(categories__price__isnull=false) | q(categories__color='blue')) 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -