Skip to main content
 首页 » 编程设计

python之如何在 Django 中按价格范围过滤对象

2025年05月04日32www_RR

我有一个模型Item,字段为price。

class Item(models.Model): 
    title = models.CharField(max_length=200, blank='true') 
    price = models.IntegerField(default=0) 

我的查询可能包含 min_price 和 max_price 值。所以,我的请求可能是这样的:http://example.com/api/items?min_price=50&max_price=500。谁能告诉我,如何查询最小值和最大值之间的项目?我可以使用 Django ORM 解决它吗?

谢谢!

请您参考如下方法:

检查 range 的 API 引用.就像它说的那样

You can use range anywhere you can use BETWEEN in SQL — for dates, numbers and even characters.

因此,在您的情况下:

Item.objects.filter(price__range=(min_price, max_price))