2023-03-07 17:23:39 +08:00
|
|
|
from rest_framework import serializers, mixins
|
2023-03-07 19:28:38 +08:00
|
|
|
from django.contrib.auth.models import User
|
2023-03-07 17:23:39 +08:00
|
|
|
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):
|
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(
|
|
|
|
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
|
2023-03-07 19:28:38 +08:00
|
|
|
fields = ('history_id', 'name', 'quantity',
|
|
|
|
'history_date', 'history_user_id')
|
|
|
|
read_only_fields = ('history_id', 'name', 'quantity',
|
|
|
|
'history_date', 'history_user_id')
|