查询集过滤器:自动生成 Q 对象和过滤器 (Django)

Queryset filters: Q objects and filters auto generation (Django)

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

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

你可以坚持使用 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)