【问题标题】:How to get sum of values from a ManyToMany relation in Django REST Framework如何从 Django REST 框架中的多对多关系中获取值的总和
【发布时间】:2020-02-04 14:55:03
【问题描述】:

我正在尝试创建一个系统,让用户可以预订航班。我有两个模型,分别命名为 ItemBooking

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

创建预订时,用户可以在Item 模型中的项目之间进行选择,该模型表示为luggage_items 列表。每个项目都有一个与之相关的价格。我想在每个预订实例中添加一个名为 total_price 的字段,这是用户在预订时选择的所有项目中该实例的总金额。每当用户通过PUT 请求更改预订时,我也希望更新此内容。我不知道如何实现这一点。我尝试将以下内容添加到 Booking 模型中:

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

但这不起作用,它会影响 所有 Booking 实例的 total_price

这是我的 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')

还有我的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

【问题讨论】:

    标签: django-models django-rest-framework django-serializer


    【解决方案1】:

    只需像这样更改您的属性total_price

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-23
      • 1970-01-01
      • 2017-06-28
      • 2018-10-05
      • 1970-01-01
      • 2014-12-11
      • 1970-01-01
      • 2021-11-25
      相关资源
      最近更新 更多