0
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

1 Answer 1

3

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'))
Sign up to request clarification or add additional context in comments.

4 Comments

Why not pass the Loss.objects.all() queryset straight in the filter?
Because that will return a list of Loss objects.
what can't i use aggregate here instead of annotate. it will return sum of qty.
I got my answer with aggregate

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.