Django Tastypie Advanced Filtering: How to do complex lookups with Q objects

后端 未结 3 1831
遥遥无期
遥遥无期 2020-12-02 20:51

I have a basic Django model like:

class Business(models.Model):
    name = models.CharField(max_length=200, unique=True)
    email = models.EmailField()
             


        
3条回答
  •  温柔的废话
    2020-12-02 21:12

    Taking the idea in astevanovic's answer and cleaning it up a bit, the following should work and is more succinct.

    The main difference is that apply_filters is made more robust by using None as the key instead of custom (which could conflict with a column name).

    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()
    

提交回复
热议问题