如何在 Django Rest Framework 上显示 ManytoMany 模型关系变量的值

How to display value of ManytoMany model relation variable on Django Rest Framework

我是 django 的新手并且正在苦苦挣扎,我查看了 google 但找不到任何可以帮助的东西。

这是我的模型:

from django.db import models
# from django.contrib.auth.models import


class Order(models.Model):

    table_id = models.IntegerField(unique=True)
    meal = models.ManyToManyField('meals')

    # Meal = models.ForeignKey('Meals',on_delete=models.CASCADE)
    @property
    def total_price(self):
        price = self.meal.objects.all().aggregate(total_price=models.Sum('meals__price'))
        return price['total_price']

class Meals(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(decimal_places=2, max_digits=5)

这是我的 serializer.py :

from rest_framework import serializers


from cafe_app import models
class MealSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Meals
        fields = ['id','name','price',]

class OrderSerializer(serializers.ModelSerializer):

    **meal = MealSerializer(read_only=True,many=True)**
    class Meta:
        model = models.Order
        fields = ['table_id','meal',]

当我评论 meal = MealSerializer(read_only=True,many=True) 行时,它显示输入为 table_id 和 meal,其中膳食值作为 Meal Object (1),Mean Object (2) ...

我的问题:

  1. 如何显示膳食对象值而不是它作为对象。
  2. 如何在 view/serializer.
  3. 中使用 total_price 方法
  4. 如何查看流程,例如它如何从 class 流向 class 调用以及我收到的结构的类型和值是什么。

谢谢。

  1. How to display meal Object value instead of it as object.

在 Meal 上使用 __str__ 方法。

  1. How Can I use total_price method in my view/serializer.

在视图的查询集中定义注释,然后将自定义字段添加到序列化程序。不要将它添加到您的模型中,除非它是一次性的。您拥有它的方式非常低效,因为它会为列表视图生成许多查询。

  1. How to see the flow like how it flows from which class to which class call goes and what is type and value of structure that I received.

在 IDE 中使用调试器,例如 PyCharm、PDB 或经典的 print 语句。

以下是我针对 1 和 2 建议的更正。

# models.py
from django.db import models

class Order(models.Model):

    table_id = models.IntegerField(unique=True)
    meal = models.ManyToManyField('meals')


class Meals(models.Model):
    name = models.CharField(max_length=100)
    price = models.DecimalField(decimal_places=2, max_digits=5)

    def __str__(self):
        # This method defines what the string representation an instance.
        return f'{self.name}: ${self.price}'


# serializers.py
from rest_framework import serializers


from cafe_app import models
class MealSerializer(serializers.ModelSerializer):

    class Meta:
        model = models.Meals
        fields = ['id','name','price',]


class OrderSerializer(serializers.ModelSerializer):
    total_price = serializers.FloatField(read_only=True)
    meal = MealSerializer(read_only=True,many=True)
    class Meta:
        model = models.Order
        fields = ['table_id','meal', 'total_price']


# views.py
class OrderView(ViewSet): # or View.

    queryset = Order.objects.annotate(
        total_price=Sum('meal__price')
    )