我想按照用戶指定的價格(最小和最大價格)過濾我的產品列表。我有兩個輸入框來取價格區間。'價格'是我數據庫表中的一列。 int()參數必須是一個字符串或數字,而不是'dict'。我包含了我的模板文件和一小部分視圖文件。如何過濾django中產品的價格範圍?
Models.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_price1 = request.GET.get(「MIN_PRICE」)''打印filter_price1 ' –
它以unicode數字格式正確打印 – Bhanukiran