serializers.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from rest_framework import serializers
  2. from .models import Transaction
  3. from django.utils.translation import ugettext_lazy as _
  4. from django.contrib.auth import get_user_model
  5. User = get_user_model()
  6. class CreateTransactionSerializer(serializers.ModelSerializer):
  7. user_id = serializers.PrimaryKeyRelatedField(
  8. queryset=User.objects.all(), source='user', write_only=True, help_text='User Id')
  9. def __init__(self, *args, **kwargs):
  10. many = kwargs.pop('many', True)
  11. super(CreateTransactionSerializer, self).__init__(many=many, *args, **kwargs)
  12. def validate(self, data):
  13. """
  14. Check the type is outflow or inflow
  15. Check the inflow is positive and outflow is negative
  16. """
  17. if data['type'] not in ('outflow','inflow'):
  18. raise serializers.ValidationError({"type": _("Must be `outflow` or `inflow` ")})
  19. if data['amount'] > 0 and data['type'] == 'outflow':
  20. raise serializers.ValidationError({"amount":_("Outflow type only allow negatives amount")})
  21. if data['amount'] < 0 and data['type'] == 'inflow':
  22. raise serializers.ValidationError({"amount":_("Inflow type only allow positives amount")})
  23. return data
  24. class Meta:
  25. model = Transaction
  26. fields = ('user_id', 'reference', 'account', 'type', 'amount', 'category','date')
  27. class BalanceByAccountSerializer(serializers.ModelSerializer):
  28. balance = serializers.FloatField(label='balance', read_only=True)
  29. total_inflow = serializers.FloatField(label='balance', read_only=True)
  30. total_outflow = serializers.FloatField(label='balance', read_only=True)
  31. class Meta:
  32. model = Transaction
  33. fields = ['account', 'balance','total_inflow','total_outflow']