afi
afi

Reputation: 603

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"

Upvotes: 0

Views: 508

Answers (2)

afi
afi

Reputation: 603

you need to define a function in signals with m2m_changed i think this is the better way if you want to save the total_price into Database. Thanks to all of you guys for helping me. this code is working for me fine. :)

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)

Upvotes: 0

Dimitar
Dimitar

Reputation: 520

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

Upvotes: 1

Related Questions