How can I chain Django's “in” and “iexact” queryset field lookups?

前端 未结 3 1513
轻奢々
轻奢々 2020-12-15 06:33

I have a list of names, e.g.:

name_list = [\'Alpha\', \'bEtA\', \'omegA\']

Currently I have the following queryset:

MyModel         


        
相关标签:
3条回答
  • 2020-12-15 06:42

    Here is an example using a list comprehension. It is similar to catherine's answer, but with one database hit like Derek Kwok's answer (but procedural instead of functional).

    q_list = Q()
    for q in [Q(name__iexact=n) for n in name_list]:
        q_list |= q
    MyModel.objects.filter(q_list)
    

    For those that like to avoid zip, map, reduce, and such in Python.

    0 讨论(0)
  • 2020-12-15 07:05

    Here's my solution, which uses Q objects instead:

    name_list = ['Alpha', 'bEtA', 'omegA']
    q_list = map(lambda n: Q(name__iexact=n), name_list)
    q_list = reduce(lambda a, b: a | b, q_list)
    MyModel.objects.filter(q_list)
    
    0 讨论(0)
  • 2020-12-15 07:08
    name_list = ['Alpha', 'bEtA', 'omegA']
    results = MyModel.objects.none()
    for name in name_list:
        results |= MyModel.objects.filter(name__iexact=name)
    

    Ok I test it and it works :)

    0 讨论(0)
提交回复
热议问题