如何获得书籍django的总价?

how to get total price of books django?

如果我在商店中添加一些书籍,那么我如何才能获得商店中所选书籍的total_price?

信号不工作它们不是 calculating anything. i want to calculate the selected books. after submitting the form i got nothing in total price is still (0)。

signals.py code

models.py code

店铺

from django.db import models

class Book(models.Model):
    name = models.CharField(max_length=100)
    price = models.IntegerField(default=0)


class Store(models.Model):     
    keeper = models.ForeignKey(User, on_delete=models.SET_NULL,null=True)
    books = models.ManyToManyField(Book)
    total_price = models.IntegerField(default=0)

signals.py

from django.db.models import Sum
from django.db.models.signals import pre_save
from django.dispatch import receiver

from .models import Store
from .models import Book


@receiver(pre_save, sender=Store)
def save_total_price(sender, instance, **kwargs):
    instance.total = Book.objects.all().aggregate(Sum("price"))["price__sum"]

apps.py

from django.apps import AppConfig


class ReportConfig(AppConfig):
    name = 'report'

    def ready(self):
        import report.signals

init.py

default_app_config = "report.apps.ReportAppConfig"

你可以为此使用一个信号。

在您的应用程序中创建文件 singals.py

@receiver(pre_save, sender=Store)
def save_total_price(sender, instance, **kwargs):
    instance.total = Book.objects.all().aggregate(Sum("price"))["price__sum"]

像这样在 App 的配置中连接您的信号:

# app.py
class WhateverAppConfig(AppConfig):
    name = "{app_path}"

    def ready(self):
        import {app_path}.signals

现在在应用程序的 __init__.py 中点配置,如下所示:

default_app_config = "{app_path}.apps.WhateverAppConfig"

其他解决方案可能包括保存该信息的缓存变量(我认为这是更好的方法)。

你需要用 m2m_changed 在信号中定义一个函数,我认为如果你想将 total_price 保存到数据库中,这是更好的方法。感谢你们所有人对我的帮助。这段代码对我来说很好。 :)

def save_total_price(sender, instance, action, *args, **kwargs):
    if action in ['post_add', 'post_remove', 'post_clear']:
        books = instance.books.all()
        instance.total_price = 0
        for book in books:
            instance.total_price += book.price
            instance.save()


m2m_changed.connect(save_total_price, sender=Patient.books.through)