rgm
rgm

Reputation: 1281

Get sum of foreign key attribute using django

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)

how can i know how much quantity is lost if the sales_id is in loss table , then the sale is lost

Upvotes: 0

Views: 1399

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174624

You need to use Sum from aggregates:

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

You really need to optimize your models:

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)

Now you can do this:

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

Upvotes: 3

Related Questions