0

Вопрос такой, мне необходимо при get запросе отобразить меню и продукты внутри ресторана примерно:

{
    "restaurant": [
        {
            "restaurant_id": 1,
            "restaurant_name": "Test_restaurant",
            "menu": {"dish_id": 1,
                     "dish_name": "Test_name",
                     "dish_price": 100} 
        },

Сейчас это выглядит:

{
    "restaurant": [
        {
            "restaurant_id": 1,
            "restaurant_name": "Test_restaurant",
            "menu": 1
        },

models.py

from django.db import models


# Create your models here.
class Restaurant(models.Model):
    restaurant_id = models.IntegerField()
    restaurant_name = models.CharField(max_length=150)
    menu = models.ForeignKey('Menu', related_name='menus', on_delete=models.CASCADE)

    def __str__(self):
        return self.restaurant_name


class Dish(models.Model):
    dish_id = models.IntegerField()
    dish_name = models.CharField(max_length=100)
    dish_price = models.IntegerField()

    def __str__(self):
        return self.dish_name

class Menu(models.Model):
    dish = models.ManyToManyField('Dish', related_name='dishes')

    def __str__(self):
        return f'Menu'

serializers.py

from rest_framework import serializers
from .models import Restaurant, Menu, Dish


class MenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = Menu
        fields = 'dish'



class DishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dish
        fields = ('dish_id', 'dish_name', 'dish_price')

   


class RestaurantSerializer(serializers.ModelSerializer):
    
    menus = MenuSerializer(many=True, read_only=True)
    dishs = DishSerializer(many=True, read_only=True)

    class Meta:
        model = Restaurant
        fields = ('restaurant_id', 'restaurant_name', 'menu','menus', 'dishs')

    def create(self, validated_data):
        return Restaurant.objects.create(**validated_data)

views.py

from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Restaurant
from .serializers import RestaurantSerializer

class RestaurantView(APIView):
    def get(self, request):
        restaurant = Restaurant.objects.all()
        serializer = RestaurantSerializer(restaurant, many= True)
        return Response({'restaurant': serializer.data})

    def  post(self, request):
        restaurant = request.data.get('restaurant')
        serializer = RestaurantSerializer(data = restaurant)
        if serializer.is_valid(raise_exception=True):
            restaurant_save = serializer.save()
        return Response({"success": "restaurant '{}' создан".format(restaurant_save.title)})
1
  • DishSerializer нужно вложить в MenuSerializer судя по вашим моделям.
    – 5c0rp
    Commented 29 дек. 2020 в 9:07

1 ответ 1

0
class DishSerializer(serializers.ModelSerializer):
    class Meta:
        model = Dish
        fields = '__all__'


class MenuSerializer(serializers.ModelSerializer):
    dish = DishSerializer(many=True, read_only=True)

    class Meta:
        model = Menu
        fields = '__all__'   


class RestaurantSerializer(serializers.ModelSerializer):
    
    menu = MenuSerializer(read_only=True)

    class Meta:
        model = Restaurant
        fields = '__all__'

    def create(self, validated_data):
        return Restaurant.objects.create(**validated_data)

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.