获取相关模型的数量

时间:2019-01-12 21:01:39

标签: python django python-3.x django-models django-views

我有2个模型,分别代表产品的 Item 和代表每个序列化产品的 OnHand 。它们受 product_id 的ForeignKey约束。

项目模型:

class Item(models.Model):
    name = models.CharField(max_length=100)
    description = models.CharField(max_length=100)
    manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL)
    introduction = models.DateField(auto_now=True)
    is_retired = models.BooleanField(default=False)
    tags = models.ManyToManyField(Tag)

    def __str__(self):
        return self.name

现有模型:

class OnHand(models.Model):
    name = models.CharField(max_length=100)
    serial = models.CharField(max_length=80)
    asset = models.CharField(max_length=20)
    product = models.ForeignKey(Item, blank=True, null=True, on_delete=models.CASCADE)


    def __str__(self):
        return self.serial

在我的索引视图上,我有一张表,显示这些产品并计算数量。为此,我需要计算具有匹配的 product_id OnHand 对象的数量。

索引:

def index(request):
    items = Item.objects.all()
    quanity = count_onhand(items)
    context = {
        'items':items,  
    }
    print(items)
    return render(request, 'index.html', context)

现有数量:

def count_onhand(items):
        for item in items:
                count = OnHand.objects \
                .filter(product_id=item.product_id) \
                .count()

由于这些对象要使用相同的视图,并且需要维持其顺序,因此我认为最好的方向是将 Item 查询集附加到随后将与原始商品,并附加了数量。

编辑:我发现上面的方法不是一个明智的方法,但是将其留在上下文中。

我要做的是获取与给定 Item 相关的所有 OnHand 对象的计数。 prefetch_related()似乎很接近我想要的,但据我所知似乎只能用于多对多。

我可以使用OnHand.objects.filter(product_id=item.pk).count(),但是我不确定这是否是最标准的方法。

1 个答案:

答案 0 :(得分:2)

  

我要做的是获取与给定项目相关的所有OnHand对象的计数。

只需使用查询api:

some_item.onhand_set.count()

如果要计算集合或项目的数量:

from django.db.models import Count
items = ( Item
         .objects
         .filter( some condition )
         .annotate(num_onhand=Count('onhand'))
         )

django Aggregation docs处的更多示例