1

我正在尝试创建一个系统,用户可以预订航班。我有两个名为Item和的模型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}"

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

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

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

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

4

1 回答 1

3

total_price像这样改变你的财产

@property
def total_price(self):
    queryset = self.luggage_items.all().aggregate(
        total_price=models.Sum('item_price'))
    return queryset["total_price"]
于 2020-02-04T17:52:04.450 回答