我正在尝试按用户指定的价格(最低和最高价格)筛选我的产品列表。我有两个用于获取价格范围的输入框。“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')
按如下方式使用聚合(cheatsheet)来确定最大值
price
:另一方面,为什么要对
^{pr2}$text
输入使用price
,我假设它是DecimalField
?如何使用数字输入(或django form)来确保视图中的强制转换不会引发错误:也许这行错了
filter_price2=Add_prod.objects.all().aggregate(Max('price'))
因为艾格盖特会回一个口述参见本文档Aggragation
试试这个:
my_products=Add_prod.objects.filter(price__range(filter_price1,filter_price2['price_max']))
相关问题 更多 >
编程相关推荐