Django сериализаторы validated_data.pop ('grocery_menu_price') не работают должным образом - PullRequest
0 голосов
/ 27 мая 2020

У меня проблема с Validated_data.pop (). Я использую Django и Python3. Мои представления:

class RestaurantMenuView(viewsets.ModelViewSet):

    def create(self,request):
        ''' add restaurant menu item detail '''
        serializer = AllMenuSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response({"success":True,"message":"Created sucessfully",
                         "data":serializer.data},
                         status=status.HTTP_201_CREATED)

    def list(self,request):
        try:
            print(request.GET.get('restaurant'))
            restaurants = Restaurant.objects.get(id=request.GET.get('restaurant'))

            serializer = RestoActiveMenuSerializer(instance=restaurants)
            return Response({"success":True,"restaurants_menu":serializer.data},
                                status=status.HTTP_200_OK)
        except Exception as e:
            print("Exception",e)
            return Response({"success":False,"message": "Something went wrong!"},
                            status=status.HTTP_400_BAD_REQUEST )

Вот мой класс сериализатора -

class GroceryMenuUnits(serializers.ModelSerializer):
    measuring_unit = serializers.SerializerMethodField()
    def get_measuring_unit(self,obj):
        return Measurements.objects.get(measurement=obj.measuring_unit).measurement if Measurements.objects.get(measurement=obj.measuring_unit).measurement else None
    class Meta:
        model = GroceryMeasurmentsQuantity
        fields = '__all__'

    class GroceryAllMenuSerializer(serializers.ModelSerializer):
    grocery_menu_price = GroceryMenuUnits(many=True)

    def create(self, validated_data):
        grocery_menu_data = validated_data 
        grocery = validated_data.pop('grocery')
        category = validated_data.pop('category')
        grocery_menu_price = validated_data.pop('grocery_menu_price')
        print(grocery_menu_price)

        grocery_menu = GroceryMenu.objects.create(grocery=grocery,**grocery_menu_data)
        for category in category:
            grocery_menu.category.add(category)

        for unit in grocery_menu_price:
            print('quantity-------------------',unit['quantity'],unit['measuring_unit']) 
            measurement = unit['measuring_unit'] if unit['measuring_unit'] else None
            GroceryMeasurmentsQuantity.objects.create(grocery_menu=grocery_menu,measuring_unit=measurement,**unit)
        grocery_menu.save()
        return grocery_menu
    class Meta:
        model = GroceryMenu
        fields = ('grocery','category','item_name','type_item','image','description','stock','available','grocery_menu_price')

Здесь, когда я печатаю print(grocery_menu_price), он печатает только цену и количество -

> [OrderedDict([('quantity', Decimal('2.00000')), ('price',
> Decimal('250.00000'))]), OrderedDict([('quantity',
> Decimal('1.00000')), ('price', Decimal('250.00000'))])] Internal
> Server Error: /api/restaurant/v2/grocery-menu/ Traceback (most recent
> call last):   File
> "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/exception.py",
> line 34, in inner
>     response = get_response(request)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/base.py",
> line 115, in _get_response
>     response = self.process_exception_by_middleware(e, request)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/base.py",
> line 113, in _get_response
>     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py",
> line 54, in wrapped_view
>     return view_func(*args, **kwargs)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/viewsets.py",
> line 114, in view
>     return self.dispatch(request, *args, **kwargs)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 505, in dispatch
>     response = self.handle_exception(exc)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 465, in handle_exception
>     self.raise_uncaught_exception(exc)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 476, in raise_uncaught_exception
>     raise exc   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 502, in dispatch
>     response = handler(request, *args, **kwargs)   File "/home/vibhu/Desktop/enigma/enigma/restaurant_app/views.py", line 325,
> in create
>     serializer.save()   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/serializers.py",
> line 212, in save
>     self.instance = self.create(validated_data)   File "/home/vibhu/Desktop/enigma/enigma/restaurant_app/serializers.py",
> line 128, in create
>     print('quantity-------------------',unit['quantity'],unit['measuring_unit'])
> KeyError: 'measuring_unit' [27/May/2020 13:27:43] "POST
> /api/restaurant/v2/grocery-menu/?grocery=1 HTTP/1.1" 500 18582
> [OrderedDict([('quantity', Decimal('2.00000')), ('price',
> Decimal('250.00000'))]), OrderedDict([('quantity',
> Decimal('1.00000')), ('price', Decimal('250.00000'))])] Internal
> Server Error: /api/restaurant/v2/grocery-menu/ Traceback (most recent
> call last):   File
> "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/exception.py",
> line 34, in inner
>     response = get_response(request)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/base.py",
> line 115, in _get_response
>     response = self.process_exception_by_middleware(e, request)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/core/handlers/base.py",
> line 113, in _get_response
>     response = wrapped_callback(request, *callback_args, **callback_kwargs)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/django/views/decorators/csrf.py",
> line 54, in wrapped_view
>     return view_func(*args, **kwargs)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/viewsets.py",
> line 114, in view
>     return self.dispatch(request, *args, **kwargs)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 505, in dispatch
>     response = self.handle_exception(exc)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 465, in handle_exception
>     self.raise_uncaught_exception(exc)   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 476, in raise_uncaught_exception
>     raise exc   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/views.py",
> line 502, in dispatch
>     response = handler(request, *args, **kwargs)   File "/home/vibhu/Desktop/enigma/enigma/restaurant_app/views.py", line 325,
> in create
>     serializer.save()   File "/home/vibhu/Desktop/enigma/venv/lib/python3.7/site-packages/rest_framework/serializers.py",
> line 212, in save
>     self.instance = self.create(validated_data)   File "/home/vibhu/Desktop/enigma/enigma/restaurant_app/serializers.py",
> line 128, in create
>     print('quantity-------------------',unit['quantity'],unit['measuring_unit'])
> KeyError: 'measuring_unit'

и я отправляю данные из Postman, тело:

> {     "grocery": 1,
>     "category": [
>         1
>     ],
>     "item_name": "milk-shake",
>     "type_item": "Veg",
>     "image": "http://localhost:8000/api/restaurant/v1/restaurants-menu/",
>     "description": "this is a good shake",
>     "stock": 22,
>     "available": true,
>     "grocery_menu_price":[{       "quantity":2.0,         "price":250,
>       "measuring_unit":1
>     },        {       "quantity":1.0,         "price":250,        "measuring_unit":1      }]
>        }

Вот моя модель -

class GroceryMenu(AbstractTime):
    grocery = models.ForeignKey(Grocery,
                                    on_delete=models.CASCADE,
                                    related_name="grocery_menu",
                                    null=True, blank=True )
    category = models.ManyToManyField(GroceryItemsCategory)

    item_name = models.CharField(max_length=120,null=True)
    type_item = models.CharField(choices=ITEM_TYPE, max_length=20)
    image =  models.URLField(max_length=254)
    description = models.TextField(blank=True)
    stock = models.PositiveIntegerField(null=True)
    available = models.BooleanField('Available',default=True)
    is_bestseller = models.BooleanField('BestSeller',default=False)
    is_active = models.BooleanField('Active', default=True)
    is_deleted = models.BooleanField(default=False)

class GroceryMeasurmentsQuantity(AbstractTime):
    grocery_menu = models.ForeignKey(GroceryMenu, on_delete=models.CASCADE, null=True, related_name="grocery_menu_price")
    measuring_unit = models.ForeignKey(Measurements, on_delete=models.CASCADE, null=True, related_name="menu_measuring_unit")
    quantity = models.DecimalField(max_digits=10,null=True,decimal_places=5)
    price = models.DecimalField(max_digits=10,null=True,decimal_places=5)

Почему я не могу найти measure_unit?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...