tree em
tree em

Reputation: 21781

filter from an object and more object that related in django?

This Is my models.py

class Customer(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField(max_length=200)
    type = models.ForeignKey(Customer_Type)
    active = models.BooleanField(default=True)

class Sale(models.Model):
    def __unicode__(self):
        return "Sale %s (%i)" % (self.type, self.id)
    customer = models.ForeignKey(Customer)
    total = models.DecimalField(max_digits=15, decimal_places=3)

class Unitary_Sale(models.Model):
    book = models.ForeignKey(Book)
    quantity = models.IntegerField()
    unit_price = models.DecimalField(max_digits=15, decimal_places=3)
    sale = models.ForeignKey(Sale)

Views.py

def get_filter_result(self, customer_type='' volume_sale=''):
        qdict = {}
        if customer_type != '':
            qdict['type__name'] = customer_type
            qdict['active']=True
        #WHAT I AM GOING TO DO NEXT
   ***  if volume_sale != '':
            pass # This point I am asking :)
        #IT RETURN CUSTOMERS BASE ON PARAMS.
        queryset = Customer.objects.filter(**qdict)

***The volume_sale is:

units=Unitary_Sale.objects.all()
>>> units=Unitary_Sale.objects.all()
>>> for unit in units:
...    print unit.sale.customer
...    print unit.book,unit.sale.total
...
Sok nara
Khmer Empire (H001) 38.4
Sok nara
killing field (H001) 16

San ta
khmer krom (H001) 20
San ta
Khmer Empire (H001) 20
>>>
{<Customer: Sok nara>: Decimal("56.4"), <Customer: san ta>: Decimal("40")}

Decimal("56.4") , Decimal("40") this is the volume_sale

I could not find the ways to make the filter from difference object as in my case. It will be great if everyone here help in this stuck? Thanks.

Upvotes: 0

Views: 179

Answers (1)

JudoWill
JudoWill

Reputation: 4811

Cool, this actually pretty easy to implement. I used the django annotation feature documented here and here:

from django.db.models import Sum
query = Customer.objects.all().annotate(volume_sale = Sum('Sale__total'))
query.filter(volume_sale < 12.0) #return all customers that have purchased less than 12.0
query[0].volume_sale #you can even get it on the Customer objects given back

Django will take care of the database joins for you. It will put this extra field into each instance of the model that you can filter, order_by and access in templates or views.

Upvotes: 2

Related Questions