Updated transaction serializer to include id and name of borrower and of equipments

This commit is contained in:
Keannu Bernasol 2023-12-14 19:27:49 +08:00
parent 1e8af2173f
commit 31b527cd9d
2 changed files with 29 additions and 4 deletions

View file

@ -7,12 +7,29 @@ from accounts.models import CustomUser
from config.settings import DEBUG from config.settings import DEBUG
class CustomUserSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='__str__')
class Meta:
model = CustomUser
fields = ['id', 'name']
class EquipmentInstanceSerializer(serializers.ModelSerializer):
name = serializers.CharField(source='equipment.name')
class Meta:
model = EquipmentInstance
fields = ['id', 'name']
class TransactionSerializer(serializers.HyperlinkedModelSerializer): class TransactionSerializer(serializers.HyperlinkedModelSerializer):
borrower = serializers.SlugRelatedField( borrower = serializers.SlugRelatedField(
many=False, slug_field='id', queryset=CustomUser.objects.all(), required=False, allow_null=True) many=False, slug_field='id', queryset=CustomUser.objects.all(), required=True, allow_null=False)
teacher = serializers.SlugRelatedField(
many=False, slug_field='id', queryset=CustomUser.objects.all(), required=True, allow_null=False)
equipments = serializers.SlugRelatedField( equipments = serializers.SlugRelatedField(
many=True, slug_field='id', queryset=EquipmentInstance.objects.filter(status="Working"), required=False) many=True, slug_field='id', queryset=EquipmentInstance.objects.all(), required=True)
transaction_status = serializers.ChoiceField( transaction_status = serializers.ChoiceField(
choices=Transaction.TRANSACTION_STATUS_CHOICES) choices=Transaction.TRANSACTION_STATUS_CHOICES)
@ -23,6 +40,14 @@ class TransactionSerializer(serializers.HyperlinkedModelSerializer):
'equipments', 'transaction_status', 'timestamp'] 'equipments', 'transaction_status', 'timestamp']
read_only_fields = ['id', 'timestamp'] read_only_fields = ['id', 'timestamp']
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['borrower'] = CustomUserSerializer(instance.borrower).data
rep['teacher'] = CustomUserSerializer(instance.teacher).data
rep['equipments'] = EquipmentInstanceSerializer(
instance.equipments, many=True).data
return rep
# Do not allow deletion of transactions # Do not allow deletion of transactions
def delete(self): def delete(self):
raise exceptions.ValidationError( raise exceptions.ValidationError(

View file

@ -8,6 +8,6 @@ class TransactionViewSet(viewsets.ModelViewSet):
# Only allow GET, POST/CREATE # Only allow GET, POST/CREATE
# Transactions cannot be deleted # Transactions cannot be deleted
http_method_names = ['get', 'post'] http_method_names = ['get', 'post']
permission_classes = [IsAuthenticated] # permission_classes = [IsAuthenticated]
serializer_class = TransactionSerializer serializer_class = TransactionSerializer
queryset = Transaction.objects.all() queryset = Transaction.objects.all()