我正在尝试按用户指定的价格(最低和最高价格)过滤我的产品列表。我有两个用于获取价格范围的输入框。“价格”是我的数据库表中的列之一。我收到错误因为 int() 参数必须是字符串或数字,而不是“dict”。我已经包含了我的模板文件和一小部分 View 文件。
模型.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)
我的模板文件,
<p>Price</p>
<input type="text" name="min_price" maxlength="4" size="3" >
to <input type="text" name="max_price" maxlength="4" size="3">
<input type="submit" value="Go">
views.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')
最佳答案
也许这一行是错误的filter_price2=Add_prod.objects.all().aggregate(Max('price'))
因为聚合将返回一个字典
请参阅此文档 Aggragation
试试这个:
my_products=Add_prod.objects.filter(price__range(filter_price1,filter_price2['price_max']))
关于python - 如何在 django 中过滤产品的价格范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37760233/