serializers.py 2.0 KB

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