过滤一个对象和更多与django相关的对象?

时间:2010-01-04 08:56:58

标签: django

这是我的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)

*** volume_sale是:

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

我无法找到从差异对象制作过滤器的方法,就像我的情况一样。 如果这里的每个人都帮忙解决这个问题会很棒吗?感谢。

1 个答案:

答案 0 :(得分:2)

很酷,这实际上很容易实现。我使用了记录herehere

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将为您处理数据库连接。它会将这个额外字段放入模型的每个实例中,您可以在模板或视图中过滤,order_by和访问。