Red
Red

Reputation: 55

How to get sum of values from a ManyToMany relation in Django REST Framework

I am trying to create a system were a user can make a booking for a flight. I have two models named Item and Booking.

class Item(models.Model):
    item_name = models.CharField(max_length=100)
    item_price = models.DecimalField(max_digits=6, decimal_places=2)

    def __str__(self):
        return self.item_name


class Booking(models.Model):
    source = models.CharField(max_length=1000)
    date_booked = models.DateTimeField(auto_now_add=True)
    date_of_travel = models.DateTimeField()
    destination = models.CharField(max_length=1000)
    first_name = models.CharField(max_length=250)
    last_name = models.CharField(max_length=250)
    luggage_items = models.ManyToManyField(Item)

    def __str__(self):
        return f"{self.first_name} {self.source}-{self.destination}-{self.date_of_travel}"

When creating the booking the user can choose between items in the Item model which is represented as a list luggage_items. Each item has a price associated with it. I would like to have an additional field in each booking instance called total_price which is the total amount for that instance of all the items the user selects when making the booking. I wold also like this to be updated whenever the user alters their booking via a PUT request. I don't know how to implement this. I tried adding the following to the Booking model:

    @property
    def total_price(self):
        queryset = self.luggage_items.through.objects.all().aggregate(
            total_price=models.Sum('item__item_price'))
        return queryset["total_price"]

But that does not work, it affects the total_price for all Booking instances.

Here's my serializers.py:

from rest_framework import serializers
from .models import Item, Booking


class ItemSerializer(serializers.ModelSerializer):
    class Meta:
        model = Item
        fields = ('id', 'item_name', 'item_price')


class BookingSerializer(serializers.ModelSerializer):

    class Meta:
        model = Booking
        fields = ('id', 'source', 'destination', 'date_of_travel',
                  'first_name', 'last_name', 'luggage_items')

and my views.py

from django.shortcuts import render
from rest_framework import viewsets, permissions
from .models import Item, Booking
from .serializers import ItemSerializer, BookingSerializer

# Create your views here.


class ItemViewset(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    serializer_class = ItemSerializer


class BookingViewset(viewsets.ModelViewSet):
    queryset = Booking.objects.all()
    serializer_class = BookingSerializer

Upvotes: 1

Views: 1978

Answers (1)

Muhammad Hassan
Muhammad Hassan

Reputation: 14391

Just change your property total_price like this

@property
def total_price(self):
    queryset = self.luggage_items.all().aggregate(
        total_price=models.Sum('item_price'))
    return queryset["total_price"]

Upvotes: 3

Related Questions