from rest_framework import serializers from inventory.models import Event, Item class BasicItemSerializer(serializers.ModelSerializer): cid = serializers.SerializerMethodField() box = serializers.SerializerMethodField() file = serializers.SerializerMethodField() returned = serializers.SerializerMethodField(required=False) event = serializers.SlugRelatedField(slug_field='slug', queryset=Event.objects.all(), allow_null=True, required=False) class Meta: model = Item fields = ['cid', 'box', 'id', 'description', 'file', 'returned', 'event'] read_only_fields = ['id'] def get_cid(self, instance): return instance.container.id if instance.container else None def get_box(self, instance): return instance.container.name if instance.container else None def get_file(self, instance): if len(instance.files.all()) > 0: return sorted(instance.files.all(), key=lambda x: x.created_at, reverse=True)[0].hash return None def get_returned(self, instance): return instance.returned_at is not None