Queryset过滤器:Q对象和过滤器自动生成(Django)

时间:2018-07-11 19:19:43

标签: django django-queryset django-q

例如,我有一个用于生成过滤器参数的函数:

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对象。
有谁知道我该怎么做?

1 个答案:

答案 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)