Abhijeet Khangarot
Abhijeet Khangarot

Reputation: 1569

Django filter objects based on list values

I have a listTextField in my modal called technology. I want to filter objects based on an array, if every array value is present in the technology field.

tech = ['a','b',....] #dynamic list
mentors_list = Mentor.objects.filter(
            **{"technology__contains" : value for value in tech}) #this doesn't work

Mentor class has (among other fields) :

class Mentor(Meta):
    technology = ListTextField(
        base_field=models.CharField(max_length=20),
        size=10, max_length=(10 * 11))

Basically i want all objects in mentor_list whose technology field must contain all the values from tech array ( but may contain some extra values ).

Upvotes: 1

Views: 2915

Answers (1)

user459872
user459872

Reputation: 24562

From the documentation You can chain Q object with & to check multiple entries contains in the ListTextField.

from functools import reduce 

technologies = ['a','b'] # your dynamic list

queries = [Q(technology__contains=technology) for technology in technologies]

query = reduce(lambda x, y: x & y, queries)

mentors_list = Mentor.objects.filter(query) 

Ref: How to dynamically compose an OR query filter in Django?

Upvotes: 3

Related Questions