Search code examples
djangodjango-modelsdjango-viewsdjango-signals

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?

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

signals.py code

models.py code

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

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"

Solution

  • You can use a signal for that.

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

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