1👍
✅
Django validations are executed first, so you can set country field
as read only and prevent django model validations, then in your update/create
method, validate country and raises your error if is needed. Also you need to create your CountrySerializer
class CountrySerializer(serializers.ModelSerializer):
#country serializer fields goes here
class UserExtendedSerializer(serializers.ModelSerializer):
country = CountrySerializer(read_only=True)
class Meta:
model = UserExtended
fields = ('country',)
def check_country(self):
request = self.context['request']
data = request.data
country_data = data.get('country'):
#Validated your country data
#valid_country = .....
if not valid_country:
raise serializers.ValidationError("Select a valid country")
def create(self,validated_data):
self.check_country()
super(UserExtended,self).create(self,validated_data)
def update(self,instance,validated_data):
self.check_country()
super(UserExtended,self).update(self,instance,validated_data)
👤levi
Source:stackexchange.com