28

我有一个基本的 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',],
    }

关于如何解决这个问题的任何想法?

谢谢 - 牛顿

4

3 回答 3

42

你在正确的轨道上。但是,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方法不足以应用您的自定义过滤器键(因为没有),但是您可以快速覆盖它并添加一个称为“自定义”的特殊过滤器。在这样做时,您build_filters可以找到一个合适的过滤器,构造它的含义并将其作为自定义传递给 apply_filters,这将简单地直接应用它,而不是尝试将其值从字典中解压缩为一个项目。

于 2012-04-05T03:20:07.107 回答
0

我这样解决了这个问题:

Class MyResource(ModelResource):

  def __init__(self, *args, **kwargs):
    super(MyResource, self).__init__(*args, **kwargs)
    self.q_filters = []

  def build_filters(self, filters=None):
    orm_filters = super(MyResource, self).build_filters(filters)

    q_filter_needed_1 = []
    if "what_im_sending_from_client" in filters:
      if filters["what_im_sending_from_client"] == "my-constraint":
        q_filter_needed_1.append("something to filter")

    if q_filter_needed_1:
      a_new_q_object = Q()
      for item in q_filter_needed:
        a_new_q_object = a_new_q_object & Q(filtering_DB_field__icontains=item)
      self.q_filters.append(a_new_q_object)

  def apply_filters(self, request, applicable_filters):
    filtered = super(MyResource, self).apply_filters(request, applicable_filters)

    if self.q_filters:
      for qf in self.q_filters:
        filtered = filtered.filter(qf)
      self.q_filters = []

    return filtered

这种方法感觉比我见过的其他方法更清晰地分离了关注点。

于 2012-08-20T21:24:51.653 回答
0

将astevanovic的答案中的想法和清理一下,以下应该可以工作并且更简洁。

主要区别在于 apply_filters 通过None用作键而不是custom(可能与列名冲突)变得更加健壮。

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({None: qset}) # None is used as the key to specify that these are non-keyword filters

    return orm_filters

def apply_filters(self, request, applicable_filters):
    return self.get_object_list(request).filter(*applicable_filters.pop(None, []), **applicable_filters)
    # Taking the non-keyword filters out of applicable_filters (if any) and applying them as positional arguments to filter()
于 2017-12-05T18:07:24.150 回答