Django_rest_api/backend/ecommerce/serializers.py
devfzn e3b750bd83
Creación modelos Item y Order para app Ecommerce
Clase Item con atributos stock y precio; metodos amount,
manage_stock, check_stock, place_order.
Clase Order con atributos user, item, quantity.
Registro en panel de administración.
Serializadores de Item y Order + excepción APIException del framework.
2023-03-30 15:24:14 -03:00

45 lines
1.1 KiB
Python

from collections import OrderedDict
from .models import Item, Order
from rest_framework_json_api import serializers
from rest_framework import status
from rest_framework.exceptions import APIException
class NotEnoughStockException(APIException):
status_code = status.HTTP_400_BAD_REQUEST
default_detail = 'Sin stock suficiente'
default_code = 'invalido'
class ItemSerializer(serializers.ModelSerializer):
class Meta:
model = Item
fields = (
'title',
'stock',
'price',
)
class OrderSerializer(serializers.ModelSerializer):
item = serializers.PrimaryKeyRelatedField(queryset = Item.objects.all(), many=False)
class Meta:
model = Order
fields = (
'item',
'quantity',
)
def validate(self, res: OrderedDict):
'''
Utilizado para validar niveles de stock del Item
'''
item = res.get("item")
quantity = res.get("quantity")
if not item.check_stock(quantity):
raise NotEnoughStockException
return res