-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserializers.py
More file actions
59 lines (49 loc) · 2.89 KB
/
Copy pathserializers.py
File metadata and controls
59 lines (49 loc) · 2.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
from .models import FinancialRecords, UserProfile
from rest_framework import serializers
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ['uuid', 'user_name', 'email', 'role', 'is_active']
read_only_fields = ['uuid']
class FinancialRecordsSerializer(serializers.ModelSerializer):
class Meta:
model = FinancialRecords
fields = ['uuid', 'created_by', 'amount', 'type_of_record', 'category', 'date', 'notes', 'is_deleted']
def validate(self, data):
try:
if data is not None:
if data.get('amount') is not None and data['amount'] < 0:
raise serializers.ValidationError("Amount must be non-negative.")
if data.get('type_of_record') not in ['income', 'expense']:
raise serializers.ValidationError("Type of record must be 'income' or 'expense'.")
if data.get('category') not in ['salary', 'food', 'rent', 'investment', 'other']:
raise serializers.ValidationError("Invalid category.")
return data
except Exception as e:
raise serializers.ValidationError(str(e))
def create(self, validated_data):
try:
if validated_data is not None:
if validated_data.get('created_by') is None:
raise serializers.ValidationError("created_by field is required.")
if validated_data.get('amount') is None:
raise serializers.ValidationError("amount field is required.")
if validated_data.get('type_of_record') is None:
raise serializers.ValidationError("type_of_record field is required.")
if validated_data.get('category') is None:
raise serializers.ValidationError("category field is required.")
return super().create(validated_data)
except Exception as e:
raise serializers.ValidationError(str(e))
def update(self, instance, validated_data):
try:
if validated_data is not None:
if validated_data.get('amount') is not None and validated_data['amount'] < 0:
raise serializers.ValidationError("Amount must be non-negative.")
if validated_data.get('type_of_record') is not None and validated_data['type_of_record'] not in ['income', 'expense']:
raise serializers.ValidationError("Type of record must be 'income' or 'expense'.")
if validated_data.get('category') is not None and validated_data['category'] not in ['salary', 'food', 'rent', 'investment', 'other']:
raise serializers.ValidationError("Invalid category.")
return super().update(instance, validated_data)
except Exception as e:
raise serializers.ValidationError(str(e))