【问题标题】:How do I calculate a many-to-many sum of products如何计算产品的多对多总和
【发布时间】:2015-01-28 09:59:42
【问题描述】:

我有这个代码,但他们不计算当前的金额。我需要保存 2 次才能工作。他们需要在桌子上列出日期。

菜单类有:

product
description
price

.

from django.db import models
from django.utils.encoding import smart_unicode
from menu.models import Menu

class Order(models.Model):
    date = models.DateTimeField(auto_now_add=True, null=True)
    table = models.IntegerField(null=False, max_length=2, )
    products = models.ManyToManyField(Menu,through='OrderProduct')
    paid = models.BooleanField(default=False)
    total = models.IntegerField(,default=0,editable=False,null=True)

    def save(self, *args, **kwargs):
        self.total = 0
        for product in self.products.all():
            relationship_queryset = OrderProduct.objects.filter(order=self, product=product)
            for p in relationship_queryset.all():
                 self.total +=  p.total_products
        super(Order, self).save(*args, **kwargs)

    def __unicode__(self):
        return smart_unicode(self.table)

class OrderProduct(models.Model):
    order = models.ForeignKey(Order)
    product = models.ForeignKey(Menu)
    num_products = models.IntegerField(max_length=2)
    total_products = models.IntegerField(default=0,editable=False)

    def save(self, *args, **kwargs):
        self.total_products = (self.product.precio * self.num_products)
        super(OrderProduct, self).save(*args, **kwargs)

更新2

我使用 post_save 但返回超出最大递归深度
他们我发现了 @cached_property 的提示,并将自定义 seve 方法更改为这个缓存的属性。我不知道这是最好的方法,但正在工作。

@cached_property
def total(self):
    x = 0
    for product in self.productos.all():
        relationship_queryset = OrderProduct.objects.filter(order=self, product=product)
        for p in relationship_queryset.all():
             x +=  p.total_products
    return x

【问题讨论】:

  • 有什么问题?您在哪里需要帮助?

标签: django django-models many-to-many django-signals


【解决方案1】:

使用聚合。您不必在模型中存储总价值。每次需要时都可以查询。 https://docs.djangoproject.com/en/dev/topics/db/aggregation/

>>> OrderProduct.objects.filter(product=product).aggregate(
...    total=Sum(F('total_products'), output_field=IntegerField())
{'total': 123}

我没有测试这段代码,但你明白了。

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-23
    • 2015-05-26
    相关资源
    最近更新 更多