python - 如何在 django 中过滤产品的价格范围?

标签 python django django-views

我正在尝试按用户指定的价格(最低和最高价格)过滤我的产品列表。我有两个用于获取价格范围的输入框。“价格”是我的数据库表中的列之一。我收到错误因为 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/

相关文章:

python - 为什么在 Django 中更改模型名称时必须声明 'atomic=False'?

iphone - 如何将 XML POST 数据从 iOS 应用程序发送到 Django 应用程序?

python - 为什么 Dash-Plotly 应用程序中的 map 尺寸太小?

python - 无法使用套接字获取所需内容

python - Django:从根目录开始的多个 url 模式分布在文件中

python - 关于FK模型继承的django动态相关名称

python - 运行开发服务器时在 Django 应用程序上列出超出范围的索引

Django 说它必须是一个模型实例

python - DjangoCMS TypeError : from_db_value() missing 1 required positional argument: 'context' after upgrade to 3. 7.2 w/Django 3.0.1

python - 使用未安装的模块通过 ssh 运行远程 python 代码