代码之家  ›  专栏  ›  技术社区  ›  CodeSpent

获取相关模型的计数

  •  1
  • CodeSpent  · 技术社区  · 7 年前

    我有两个型号, 项目 代表产品,以及 手头 它表示每个单独的序列化产品。它们被一个 产品标识 .

    项目模型:

    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
    

    ONHORD模型:

    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
    

    在我身上 索引 视图,我有一个表显示这些产品并计算数量。为了做到这一点,我需要计算 手头 存在具有匹配项的对象 产品标识 .

    索引:

    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()
    

    因为这些视图是相同的,需要维护它们的顺序,所以我认为最好的方向是附加到 项目 查询集,然后附加到一个列表中,我将用原始项目返回,并附加数量。

    编辑:我发现上面的方法不明智,但把它留给上下文。

    我要做的就是数一数 手头 与给定对象相关的对象 项目 . prefetch_related() 似乎接近我想要的,但似乎只与多对多(据我所知)合作。

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

    1 回复  |  直到 7 年前
        1
  •  2
  •   dani herrera    7 年前

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

    只需使用查询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

    推荐文章