如何过滤Django产品的价格范围?

2024-05-19 05:52:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试按用户指定的价格(最低和最高价格)筛选我的产品列表。我有两个用于获取价格范围的输入框。“price”是数据库表中的一列。我遇到错误,因为int()参数必须是字符串或数字,而不是“dict”。我包含了模板文件和一小部分视图文件。在

在模型.py你说

class Add_prod(models.Model):
    book = models.CharField("Book Name",max_length=40)
    author = models.CharField("Author",max_length=30)
    price = models.PositiveIntegerField("Price")
    image = models.ImageField(upload_to='images',null=True)
    cat = models.ForeignKey(Add_cat,on_delete=models.PROTECT)

    def __unicode__(self):
        return "%s" % (self.cat)

我的模板文件

^{pr2}$

在视图.py你说

@csrf_protect  
def welcome_user(request): 
    if 'min_price' in request.GET:
        filter_price1 = request.GET.get('min_price')
        filter_price2 = request.GET.get('max_price')
        if filter_price1 =='':
            filter_price1=0
        if filter_price2=='':
            filter_price2=Add_prod.objects.all().aggregate(Max('price'))
        my_products = Add_prod.objects.filter(price__range=(filter_price1,filter_price2))
        context = { "products":my_products}
   return render(request,"welcome-user.html",context)

我也试过这样

my_products = Add_prod.objects.raw('SELECT * FROM books_add_prod where price between filter_price1 and filter_price2')

Tags: 文件addgetifmodelsrequest价格prod
2条回答

按如下方式使用聚合(cheatsheet)来确定最大值price

from decimal import Decimal as D
...
price1 = D(request.GET.get('min_price', 0)) 
price2 = D(request.GET.get('max_price', 0))

if not price2:
    price2 = Add_prod.objects.aggregate(Max('price'))['price__max']

my_products = Add_prod.objects.filter(price__range=(price1, price2))

另一方面,为什么要对text输入使用price,我假设它是DecimalField?如何使用数字输入(或django form)来确保视图中的强制转换不会引发错误:

^{pr2}$

也许这行错了filter_price2=Add_prod.objects.all().aggregate(Max('price')) 因为艾格盖特会回一个口述

参见本文档Aggragation

试试这个: my_products=Add_prod.objects.filter(price__range(filter_price1,filter_price2['price_max']))

相关问题 更多 >

    热门问题