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 know how quantity lost if sales_id in loss table , sale lost

you need use sum 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 need optimize 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 can this:

lost_sales_id = loss.objects.all().values_list('sale__pk', flat=true) salesline.objects.filter(pk__in=lost_sales_id).annotate(sum('qty')) 

Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -