Django: Query using contains each value in a list

后端 未结 5 1548
广开言路
广开言路 2020-11-27 12:07

I need to perform a django query that checks if a field contains all values within a list. The list will be of varying length

Example

User.objects.fi         


        
相关标签:
5条回答
  • 2020-11-27 12:09
    import operator
    from django.db.models import Q
    
    q = ['x', 'y', 'z']
    query = reduce(operator.and_, (Q(first_name__contains = item) for item in q))
    result = User.objects.filter(query)
    
    0 讨论(0)
  • 2020-11-27 12:14

    The accepted solution didn't work for me, but this did:

    list = ['x', 'y', 'z']
    results = User.objects.filter(first_name__contains=list[0])
    del list[0]
    
    for l in list:
        results = results.filter(first_name__contains=l)
    

    The first results variable will store a list of all the objects with the first_name name field value 'x'.

    And then in the for loop you filter for 'y' amongst the first filter results. Now you have a QuerySet that should contain a list of items where both 'x' and 'y' can be found. Now amongst those you filter for any item that contains 'z' as well.

    This should work for any length list.

    0 讨论(0)
  • 2020-11-27 12:21
    from django.db.models import Q
    User.objects.filter(Q(first_name__contains=x)&Q(first_name__contains=y)&Q(first_name__contains=z))
    

    Works for me on Django 1.8 python 2.7

    doc => https://docs.djangoproject.com/en/1.8/ref/models/querysets/#q-objects

    for more recent => https://docs.djangoproject.com/en/2.1/ref/models/querysets/#q-objects

    0 讨论(0)
  • 2020-11-27 12:30

    Just another approach.

    qs = User.objects.all()
    for search_term in ['x', 'y', 'z']:
        qs = qs.filter(first_name__contains=search_term)
    

    I'm not sure if it is better, but it's more readable.

    0 讨论(0)
  • 2020-11-27 12:33
    import operator
    from django.db.models import Q
    
    User.objects.filter(reduce(operator.and_, (Q(first_name__contains=x) for x in ['x', 'y', 'z'])))
    

    for python 3

    from functools import reduce
    

    .

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