Django:按两个整数范围过滤对象

时间:2019-05-12 14:12:43

标签: django

我有一个ID为Price_from,price_to和drive_from,driven_too的搜索表单,但是由于price和driven是相同的逻辑,因此我只关注其中之一,因为price_from和price_to不在模型中,所以它给了我错误,因为此参数不存在,因此无法进行任何比较。

如何在汽车对象中搜索价格在此范围内(price_from-price_to)的对象,我应该修改模型吗?

# model
class Car(models.Model):
    id = models.CharField(max_length=255)
    number = models.CharField(max_length=255)
    price = models.IntegerField()

# view
def search(request):
        if 'search_filter' in request.GET:
            search_params = request.GET.dict()
            search_params.pop("search_filter")
            price_from = search_params['price_from']
            price_to = search_params['price_to']
            q_list = [Q(("{}__icontains".format(param), search_params[param])) for param in search_params 
            if search_params[param] is not None]  

            my_query = Car.objects.filter(reduce(operator.and_, q_list))
            cars = [{
                'id': x.id,
                'driven': x.driven,
                'price': x.price,
            } for x in my_query
            ]
            return JsonResponse({'data': cars})
        context = {'cars': Car.objects.all().order_by('price')}
        return render(request, 'cars/car_index.html', context)

1 个答案:

答案 0 :(得分:1)

您可以使用以下方法构造Q(..)对象:

Q(price__gte=price_from, price__lte=price_to)

或者您可以使用以下方法排除边界:

Q(price__gt=price_from, price__lt=price_to)

尽管price_fromprice_to可能是None,并因此使用kwargs构造了一个Q对象:

if 'search_filter' in request.GET:
    search_params = request.GET.dict()
    search_params.pop('search_filter')
    price_from = search_params.pop('price_from', None)
    price_to = search_params.pop('price_to', None)
    q_list = [
        Q(('{}__icontains'.format(k), v))
        for k, v in search_params.items()
        if v is not None
    ]
    price = { 'price__gte': price_from, 'price__lte': price_to }
    q_list.append(Q(**{k: int(v) for k, v in price.items() if v is not None}))
    # ...