Files
zod-backend/zod_bank/junior/serializers.py
2023-06-23 19:13:49 +05:30

74 lines
3.1 KiB
Python

from rest_framework import serializers
from django.contrib.auth.models import User
from .models import Guardian
from django.db import transaction
import random
from account.models import UserProfile
from junior.models import Junior
from base.constants import GENDERS, GUARDIAN, JUNIOR, SUPERUSER
from rest_framework_simplejwt.tokens import RefreshToken
from base.messages import ERROR_CODE, SUCCESS_CODE
from django.contrib.postgres.fields import ArrayField
class ListCharField(serializers.ListField):
child = serializers.CharField()
def to_representation(self, data):
return data
def to_internal_value(self, data):
if isinstance(data, list):
return data
raise serializers.ValidationError({"details":"Invalid input. Expected a list of strings."})
class CreateJuniorSerializer(serializers.ModelSerializer):
first_name = serializers.SerializerMethodField('get_first_name')
last_name = serializers.SerializerMethodField('get_last_name')
email = serializers.SerializerMethodField('get_email')
phone = serializers.CharField(max_length=20, required=False)
country_code = serializers.IntegerField(required=False)
dob = serializers.DateField(required=False)
referral_code = serializers.CharField(max_length=100, required=False)
guardian_code = ListCharField(required=False)
class Meta(object):
model = Junior
fields = ['first_name', 'last_name', 'email', 'phone', 'gender', 'country_code', 'dob', 'referral_code',
'passcode', 'is_complete_profile', 'guardian_code']
def get_first_name(self,obj):
return obj.auth.first_name
def get_last_name(self,obj):
return obj.auth.last_name
def get_email(self,obj):
return obj.auth.email
def create(self, validated_data):
user = User.objects.filter(username=self.context['user']).last()
if user:
user.first_name = self.context.get('first_name', user.first_name)
user.last_name = self.context.get('last_name', user.last_name)
user.save()
junior, created = Junior.objects.get_or_create(auth=self.context['user'])
if created:
junior.referral_code = ''.join([str(random.randrange(9)) for _ in range(4)])
junior.junior_code = ''.join([str(random.randrange(9)) for _ in range(4)])
if junior:
junior.phone = validated_data.get('phone', junior.phone)
junior.gender = validated_data.get('gender',junior.gender)
junior.guardian_code = validated_data.get('guardian_code', junior.guardian_code)
junior.dob = validated_data.get('dob',junior.dob)
junior.passcode = validated_data.get('passcode', junior.passcode)
junior.is_complete_profile = validated_data.get('is_complete_profile', junior.is_complete_profile)
junior.country_code = validated_data.get('country_code', junior.country_code)
junior.save()
return junior
def save(self, **kwargs):
with transaction.atomic():
instance = super().save(**kwargs)
return instance