代码之家  ›  专栏  ›  技术社区  ›  tree em

从一个对象和更多与Django相关的对象中筛选?

  •  0
  • tree em  · 技术社区  · 15 年前

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

    VIEW

    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)
    

    ***销售量为:

    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
    

    我找不到像在我的例子中那样从Difference对象中创建过滤器的方法。 如果这里的每个人都能帮上忙,那就太好了?谢谢。

    1 回复  |  直到 15 年前
        1
  •  2
  •   JudoWill    15 年前

    很酷,这其实很容易实现。我使用了记录的django注释功能 here 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将为您处理数据库连接。它将把这个额外的字段放入模型的每个实例中,您可以在模板或视图中进行筛选、排序和访问。