一尘不染

Django Deliciousp高级过滤:如何使用Q对象进行复杂的查找

django

我有一个基本的Django模型,例如:

class Business(models.Model):
    name = models.CharField(max_length=200, unique=True)
    email = models.EmailField()
    phone = models.CharField(max_length=40, blank=True, null=True)
    description = models.TextField(max_length=500)

我需要对上述模型执行复杂的查询,例如:

qset = (
    Q(name__icontains=query) |
    Q(description__icontains=query) |
    Q(email__icontains=query)
    )
results = Business.objects.filter(qset).distinct()

我已经尝试过以下使用法式饼的运气:

def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(BusinessResource, self).build_filters(filters)

    if('query' in filters):
        query = filters['query']
        print query
        qset = (
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(email__icontains=query)
                )
        results = Business.objects.filter(qset).distinct()
        orm_filters = {'query__icontains': results}

    return orm_filters

在梅花类的Meta类中,我将过滤设置为:

filtering = {
        'name: ALL,
        'description': ALL,
        'email': ALL,
        'query': ['icontains',],
    }

关于如何解决这个问题有什么想法吗?


阅读 597

收藏
2020-04-01

共1个答案

一尘不染

你走在正确的轨道上。但是,build_filters应该将资源查找转换为ORM查找。

默认实现将查询关键字基于__key_bits,值对进行拆分,然后尝试查找所查找资源与其等效ORM之间的映射。

你的代码不应仅在此处构建过滤器。这是一个改进的固定版本:

def build_filters(self, filters=None):
    if filters is None:
        filters = {}
    orm_filters = super(BusinessResource, self).build_filters(filters)

    if('query' in filters):
        query = filters['query']
        qset = (
                Q(name__icontains=query) |
                Q(description__icontains=query) |
                Q(email__icontains=query)
                )
        orm_filters.update({'custom': qset})

    return orm_filters

def apply_filters(self, request, applicable_filters):
    if 'custom' in applicable_filters:
        custom = applicable_filters.pop('custom')
    else:
        custom = None

    semi_filtered = super(BusinessResource, self).apply_filters(request, applicable_filters)

    return semi_filtered.filter(custom) if custom else semi_filtered

因为你使用的是Q对象,所以标准apply_filters方法不够聪明,无法应用你的自定义过滤器键(因为没有键),但是你可以快速覆盖它并添加一个名为“ custom”的特殊过滤器。这样,你build_filters可以找到一个合适的过滤器,构造它的含义,并将其作为自定义传递给apply_filters,后者将直接应用它,而不是尝试从字典中将其值作为一个项目拆包。

2020-04-01