from rest_framework import serializers from location.models import Country, Region class CountrySerializer(serializers.ModelSerializer): country_code_2 = serializers.CharField() class Meta: model = Country fields = ( "country_code_2", ) def validate(self, data): data["code"] = self.get_country_code(data) del(data['country_code_2']) return data def create(self, validated_data): # Some countries already in database country, _ = Country.objects.get_or_create(**validated_data) return Country def get_country_code(self, obj): return obj.get("country_code_2") class RegionSerializer(serializers.ModelSerializer): region_code = serializers.CharField() subregion_code = serializers.CharField(allow_null=True) country_code_2 = serializers.CharField() class Meta: model = Region fields = ( "region_code", "country_code_2", "subregion_code" ) def validate(self, data): data['code'] = data.pop('region_code') try: country = Country.objects.get(code=data['country_code_2']) except Exception as e: raise ValueError(f"{data}: {e}") data["country"] = country del (data['country_code_2']) del(data['subregion_code']) return data def create(self, validated_data): # Some regions may be already in database try: region, _ = Region.objects.get_or_create(**validated_data) except Exception as e: raise ValueError(f"{validated_data}: {e}") return region