【问题标题】:Filter with field has relationship in Django?带有字段的过滤器在Django中有关系?
【发布时间】:2009-12-31 11:20:34
【问题描述】:

我在 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)

如何过滤以获取客户销售的所有图书?

我试过了:

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
>>>

我想要什么:

  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")}

【问题讨论】:

    标签: python django django-models django-orm


    【解决方案1】:

    看看aggregation documentation

    我相信这应该可以解决问题(仅适用于 1.1 版或开发版):

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

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

    class Customer(models.Model):
        def __unicode__(self):
            return self.name
        name = models.CharField(max_length=200)
    
        def total_sale(self):
            total = 0
            for s in self.sale_set:
               total += s.total
            return total
    

    【讨论】:

    • AttributeError: 'Manager' 对象没有属性 'annotate'
    • 您使用的是哪个 Django 版本?尝试将annotate 替换为aggregate
    • 它适应了我的问题?那么我应该将它应用到我的测验中吗? :)
    • 看看我的帖子。我更改了注释以汇总相同的错误。为您的客户方法我该如何使用它?谢谢
    • 如果您在模型类中定义了一个方法,它将可用于每个客户实例。类似于Customer.objects.get(name='Sok nara').total_sale()
    猜你喜欢
    • 2019-07-06
    • 2018-05-25
    • 2021-12-09
    • 2023-03-06
    • 2020-03-19
    • 2021-12-20
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    相关资源
    最近更新 更多