带字段的过滤器在Django中有关系吗?

2024-06-16 10:32:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Django有这些模型:

class Customer(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField(max_length=200)

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)
    notes = models.TextField(blank=True, null=True)

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)

我怎样才能筛选出顾客出售的所有书籍?在

我试过了:

^{pr2}$

我想要的:

  sok nora:56.4 (38.4+18)
  san ta:40 (20+20)

或到字典:

{sok nora:156.4, san ta:40}

>>> store_resulte = {}
>>> for unit in units:
...    store_resulte[unit.sale.customer] = unit.sale.total
...
>>> print store_resulte

    {<Customer: Sok nara>: Decimal("16"), <Customer: san ta>: Decimal("20")}

它应该是:

{<Customer: Sok nara>: Decimal("56.4"), <Customer: san ta>: Decimal("40")}

Tags: storeselfmodelmodelsunitcustomersalemax
1条回答
网友
1楼 · 发布于 2024-06-16 10:32:18

看看aggregation documentation。在

我相信这应该能做到这一点(仅适用于版本1.1或dev.):

Customer.objects.annotate(total=Sum('sale__total'))

编辑:还可以为类定义自定义方法:

^{pr2}$

相关问题 更多 >