开发者社区> 问答> 正文

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

我是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',]

当我注释顿饭= MealSerializer(read_only = True,many = True)行时,它将输入显示为table_id和顿饭,其中顿饭值分别为顿饭对象(1),均值对象(2)...。

我的问题:

  1. How to display meal Object value instead of it as object.
  2. How Can I use total_price method in my view/serializer.
  3. 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.

谢谢。

问题来源:stackoverflow

展开
收起
is大龙 2020-03-24 21:49:40 645 0
1 条回答
写回答
取消 提交回答
  • 如何显示进餐对象值而不是它作为对象。

    在用餐时使用str方法。

    如何在视图/序列化器中使用total_price方法。

    在视图的查询集中定义注释,然后将自定义字段添加到序列化程序。除非它是一次性的,否则请勿将其添加到模型中。使用它的方式效率很低,因为它将为列表视图生成许多查询。

    如何看待流程,例如流程从哪个类到哪个类调用的流向以及我收到的结构的类型和值是什么。

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

    以下是我对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')
        )
    

    回答来源:stackoverflow

    2020-03-24 21:49:48
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载