2👍
✅
Maybe this line wrong filter_price2=Add_prod.objects.all().aggregate(Max('price'))
Cause aggragate will return a dict
See this docs Aggragation
Try this:
my_products=Add_prod.objects.filter(price__range(filter_price1,filter_price2['price_max']))
👤張泰瑋
1👍
Here is what worked for me, this might not be the optimal way to do it. But it works so anyone from future could give it a try:
<form method="get">
<input type="text" name="min_price" maxlength="4" size="3" required>
to <input type="text" name="max_price" maxlength="4" size="3" required>
<input type="submit" value="Go">
</form>
And In your Views:
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
products = Products.objects.filter(price__range=(filter_price1,filter_price2))
0👍
Use aggregation (cheatsheet) as follows to determine the maximum 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))
On a different note, why do you use text
inputs for price
which I assume is a DecimalField
? What about a number input (or a django form) in order to make sure that the casts in your view don’t raise errors :
<input type="number" name="min_price" min="0" step="0.01" >
- [Django]-How to set django database settings
- [Django]-Mandatory read-only fields in django
- [Django]-RequestFactory & reverse with pk (must be called with either an object pk or a slug)
Source:stackexchange.com