Django根据列表值过滤对象

时间:2018-05-29 01:15:50

标签: python django django-models filter orm

我的模态中有一个名为technology的listTextField。我想基于数组过滤对象,如果technology字段中存在每个数组值。

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

Mentor课程(以及其他领域):

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

基本上我想要mentor_listtechnology字段必须包含tech数组中所有值的所有对象(但可能包含一些额外的值)。

1 个答案:

答案 0 :(得分:2)

来自documentation您可以使用Q链接&对象,以检查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) 

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

相关问题