Search code examples
djangodjango-modelsdjango-querysetdjango-q

retrieving Django queryset in conditions' order


i'm trying to make a query that gives me the results in the order that i have the conditions in. I tried the following:

 if query:
    word_list = query.split()
    for word in word_list:
       icons = icons.filter(
                   Q(name__iexact=word) |
                   Q(name__istartswith=word) |
                   Q(words__text__icontains=word) |
                   Q(name__icontains=word)
               ).distinct()

and also

if query:
    word_list = query.split()
    for word in word_list:
       exact_icons = icons.filter(Q(name__iexact=word)).distinct()
       start_with_icons = icons.filter(Q(name__istartswith=word)).distinct()
       contains_icons = icons.filter(
                         Q(words__text__icontains=word) |
                         Q(name__icontains=word)
                     ).distinct()
       icons = exact_icons | start_with_icons | contains_icons

so i would like to first get the results that match exactly, then the ones that start with and only at end the ones that contain the word, but neither of the alternatives above seem to work. Any ideas how can i accomplish this? Thanks


Solution

  • You can use chain. It does the following:

    list_a = ['A', 'B', 'C']
    list_b = ['D', 'E', 'F']
    print(list(chain(list_a, list_b)))
    >>> ['A', 'B', 'C', 'D', 'E', 'F']
    

    Here to use in your second try:

    from itertools import chain
    ...
    icons = list(chain(exact_icons, start_with_icons, contains_icons))
    

    Due to your updated infos:

    from functools import reduce, import operator
    words_qs = reduce(operator.or_, (Q(name__iexact=word) for word in words))
    YourModel.objects.filter(..., words_qs)