SHARE
TWEET

Untitled

a guest Oct 10th, 2019 77 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. from rest_framework import serializers
  2. from accounts.models import Account
  3.  
  4.  
  5. class AccountSerializer(serializers.ModelSerializer):
  6.     class Meta:
  7.         model = Account
  8.         fields = ('id', 'owner', 'balance', 'creation_date')
  9.  
  10.     def create(self, validated_data):
  11.         if validated_data["balance"] < 0:
  12.             msg = {"message": "Não é permitido saldo negativo."}
  13.             raise serializers.ValidationError(msg)
  14.         return Account.objects.create(**validated_data)
  15.  
  16.     def update(self, instance, validated_data):
  17.         if "owner" in validated_data:
  18.             msg = {"message": "Apenas o saldo pode ser atualizado."}
  19.             raise serializers.ValidationError(msg)
  20.         if validated_data["balance"] == 0:
  21.             msg = {"message": "Valor não pode ser zero."}
  22.             raise serializers.ValidationError(msg)
  23.         elif validated_data["balance"] > 0:
  24.             instance.balance += validated_data["balance"]
  25.             instance.save()
  26.         elif validated_data["balance"] < 0:
  27.             instance.balance += validated_data["balance"]
  28.             if instance.balance < 0:
  29.                 msg = {"message": "Saldo insuficiente."}
  30.                 raise serializers.ValidationError(msg)
  31.             else:
  32.                 instance.save()
  33.         return instance
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top