How to combine multiple QuerySets in Django?

Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won’t add further cost. from itertools import chain result_list = list(chain(page_list, article_list, post_list)) Using itertools.chain is faster than looping each list and appending elements one by … Read more

Django query filter combining AND and OR with Q objects don’t return the expected results

Try adding parentheses to explicitly specify your grouping? As you already figured out, multiple params to filter() are just joined via AND in the underlying SQL. Originally you had this for the filter: […].filter( Q(hide=False) & Q(deleted=False), Q(stock=False) | Q(quantity__gte=1)) If you wanted (A & B) & (C | D) then this should work: […].filter( … Read more

django dynamically filtering with q objects

You’ll want to loop through the tag_list and apply a filter for each one. tag_list = [‘tag1’, ‘tag2’, ‘tag3’] base_qs = Design.objects.all() for t in tag_list: base_qs = base_qs.filter(tags__tag__contains=t) This will give you results matching all tags, as your example indicated with and. If in fact you needed or instead, you will probably need Q … Read more

How can I combine two or more querysets in a Django view?

Concatenating the querysets into a list is the simplest approach. If the database will be hit for all querysets anyway (e.g. because the result needs to be sorted), this won’t add further cost. from itertools import chain result_list = list(chain(page_list, article_list, post_list)) Using itertools.chain is faster than looping each list and appending elements one by … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)