如何从数量最少的 django 模型中获取前 5 名库存商品?

How can I get top 5 inventory items from a django model which has lowest quantity?

#这是我的库存模型。我想获取模型中数量最少的库存项目。

class Inventory(models.Model):
    name = models.CharField(max_length=100)
    purchase_date = models.DateTimeField()
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    
    quantity = models.CharField(max_length=50)
    purchase_price = models.FloatField(max_length=50)
    selling_price = models.FloatField(max_length=50)
    description = models.CharField(max_length=100)
    location = models.ForeignKey(Locations, on_delete=models.CASCADE)
    created_date = models.DateField(auto_now_add=True)

要获得多个具有最低或最高值的结果,您首先按该字段排序 order_by('quantity') 这样您想要的结果将排在第一位,然后您可以 slice 限制查询集结果数

quantity 字段实际上应该是 PositiveIntegerFieldIntegerField,因为它存储整数

top_five_least_quantity = Inventory.objects.order_by('quantity')[:5]