如何获得书籍django的总价? [英] how to get total price of books django?
问题描述
如果我在商店中添加了一些书,那么我如何才能在商店中获得所选书的总价?
if i add some books in store then how can i get the total_price of selected books in store?
信号不起作用,它们不是计算任何内容。我想计算选定的书。提交表格后,我的总价为仍为(0)。
signals are not working they are not calculating anything. i want to calculate the selected books. after submitting the form i got nothing in total price is still (0).
store
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
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
。
Create a file singals.py
in your application.
@receiver(pre_save, sender=Store)
def save_total_price(sender, instance, **kwargs):
instance.total = Book.objects.all().aggregate(Sum("price"))["price__sum"]
在App的Config中连接信号,如下所示:
Connect your signals in App's Config like so:
# app.py
class WhateverAppConfig(AppConfig):
name = "{app_path}"
def ready(self):
import {app_path}.signals
Now指向配置的应用程序的 __ init __。py
,如下所示:
Now point in __init__.py
of the app the config like so:
default_app_config = "{app_path}.apps.WhateverAppConfig"
其他解决方案可能包括保存该信息的缓存变量(我认为这是更好的方法)。
Other solutions might include cached variable that holds that information (which I think its the better way).
这篇关于如何获得书籍django的总价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!