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
Post a Comment