Ivy-Backend/ivy/products/serializers.py

33 lines
1.2 KiB
Python
Raw Normal View History

2023-03-07 17:23:39 +08:00
from rest_framework import serializers, mixins
from simple_history.models import HistoricalRecords
2023-03-05 21:56:48 +08:00
from .models import Product
2023-03-07 17:23:39 +08:00
class HistoricalRecordField(serializers.ListField):
child = serializers.DictField()
def to_representation(self, data):
return super().to_representation(data.values('quantity', 'history_date').order_by('-history_date'))
2023-03-07 17:23:39 +08:00
2023-03-05 21:56:48 +08:00
class ProductSerializer(serializers.HyperlinkedModelSerializer):
date_added = serializers.DateTimeField(
format="%d-%m-%Y %I:%M%p", read_only=True)
2023-03-06 15:38:47 +08:00
quantity = serializers.IntegerField(required=False, default=0)
2023-03-07 17:23:39 +08:00
history = HistoricalRecordField(read_only=True)
2023-03-05 21:56:48 +08:00
class Meta:
model = Product
2023-03-07 17:23:39 +08:00
fields = ('id', 'name', 'quantity', 'date_added', 'history')
read_only_fields = ('id', 'date_added', 'history')
class LogSerializer(serializers.HyperlinkedModelSerializer):
history_date = serializers.DateTimeField(
format="%d-%m-%Y %I:%M%p", read_only=True)
class Meta:
model = Product.history.model
fields = ('history_id', 'name', 'quantity', 'history_date')
read_only_fields = ('history_id', 'name', 'quantity', 'history_date')