例如,我有一个用于生成过滤器参数的函数:
def get_filters_parameters(name=None, mother_age=None, surname_not=None):
filters = {}
if name:
filters['name'] = name
if mother_age:
filters['mother__age'] = mother_age
# if surname_not:
# here we need `~Q(surname = surname_not)` expression
return **filters
my_filters = get_filters_parameters(name='ululu')
qs = MyModel.objects.filter(**my_filters)
我需要在surname_not
字段的过滤器参数中使用Q对象。
有谁知道我该怎么做?
答案 0 :(得分:2)
您可以坚持使用Q。
def get_filters_parameters(name=None, mother_age=None, surname_not=None):
filters = Q()
if name:
filters &= Q(name=name)
if mother_age:
filters &= Q(mother__age=mother_age)
if surname_not:
filters &= ~Q(surname=surname_not)
return filters
my_filters = get_filters_parameters(name='ululu')
qs = MyModel.objects.filter(my_filters)