使用django获取外键属性的总和

时间:2014-01-31 13:58:03

标签: django django-queryset

class sales_line(models.Model):
    sales_id = models.CharField(max_length=200)
    item = models.CharField(max_length=200)
    qty =   models.IntegerField()

    def __unicode__(self):
        return self.sales_id


class Loss(models.Models):
    sale_id = models.ForeignKey(sales_line)

我怎么知道丢失了多少数量 如果sales_id在损失表中,那么销售就会丢失

1 个答案:

答案 0 :(得分:2)

您需要使用aggregates中的Sum

from django.db.models import Sum
lost_sales_id = Loss.objects.all().values_list('sale_id__sales_id', flat=True)
total = sales_line.objects.filter(sales_id__in=lost_sales_id).annotate(Sum('qty'))

您确实需要优化模型:

class SalesLine(models.Model):
    sales_id = models.CharField(max_length=200)
    item = models.CharField(max_length=200)
    qty = models.IntegerField()

    def __unicode__(self):
        return unicode(self.sales_id)

class Loss(models.Model):
    sale = models.ForeignKey(SalesLine)

现在你可以这样做:

lost_sales_id = Loss.objects.all().values_list('sale__pk', flat=True)
SalesLine.objects.filter(pk__in=lost_sales_id).annotate(Sum('qty'))