Django filter with OR condition using dict argument

前端 未结 3 1057
没有蜡笔的小新
没有蜡笔的小新 2020-12-09 05:50

I have a function on my Django app where I perform some Queryset actions and set it\'s result to Memcache. Since it is a function it has to be of general usage. So in order

3条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-09 06:38

    Based on @Moses Koledoye's answer I could solve the issue. This is how my function looks like now:

     cached_query(key, model, my_filter=None, or_filter={}, exclude=None, order_by=None, sliced=50):
        """
        :param key: string used as key reference to store on Memcached
        :param model: model reference on which 'filter' will be called
        :param my_filter: dictionary containing the filter parameters (eg.: {'title': 'foo', 'category': 'bar'}
        :param or_filter: dictionary containing the filter parameters (eg.: {'title': 'foo', 'category': 'bar'}
        :param sliced: integer limit of results from the query. The lower the better, since for some reason Django Memcached
            won't store thousands of entries in memory
        :param exclude: dictionary containing the exclude parameters (eg.: {'title': 'foo', 'category': 'bar'}
        :param order_by: tuple containing the list of fields upon which the model will be ordered.
        :return: list of models. Not a QuerySet, since it was sliced.
        """
    
        result = cache.get(key, None)
        if not result:
            result = model.objects.all()
            if my_filter:
                result = model.objects.filter(**my_filter)
            if or_filter:
                reduced_filter = reduce(operator.or_, (Q(**d) for d in [dict([i]) for i in or_filter.items()]))
                result = result.filter(reduced_filter)
            if exclude:
                result = result.exclude(**exclude)
            if order_by:
                result = result.order_by(*order_by)
            result = result[:sliced]
            cache.set(key, result, cache_timeout)
        return result
    

提交回复
热议问题