2023-03-07 23:48:52 +08:00
|
|
|
from rest_framework import serializers
|
2023-03-07 19:28:38 +08:00
|
|
|
from django.contrib.auth.models import User
|
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):
|
2023-03-07 18:26:00 +08:00
|
|
|
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(
|
2023-03-09 23:20:36 +08:00
|
|
|
format="%m-%d-%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(
|
2023-03-09 23:20:36 +08:00
|
|
|
format="%m-%d-%Y %I:%M%p", read_only=True)
|
2023-03-07 22:20:34 +08:00
|
|
|
history_user = serializers.ReadOnlyField(source='history_user.username')
|
2023-03-07 17:23:39 +08:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = Product.history.model
|
2023-03-07 20:39:16 +08:00
|
|
|
fields = ('history_id', 'id', 'name', 'quantity',
|
2023-03-07 22:20:34 +08:00
|
|
|
'history_date', 'history_user')
|
2023-03-07 20:39:16 +08:00
|
|
|
read_only_fields = ('history_id', 'id', 'name', 'quantity',
|
2023-03-07 22:20:34 +08:00
|
|
|
'history_date', 'history_user')
|