I can save the mac_address
to upper in database
And the mac_address
value should be unique in database
But if the client send me a lower case json like {"mac_address":'aa:bb:cc:dd:eE'}
and my database already had mac_address
with 'AA:BB:CC:DD:EE'
But client still got 201 created success
Why wouldn't my UniqueValidator
work ??
Please help me find out
views.py
I try ListCreateAPIView
and APIView
Both can't work well I think the problem is UniqueValidator
part
I find the document use validate_<field_name>
But My code not work
class DataList(generics.ListCreateAPIView):
queryset = Data.objects.all()
serializer_class = DataSerializer
def perform_create(self, serializer):
mac_address = self.request.data['mac_address'].upper()
serializer.save(mac_address=mac_address, datetime=datetime.datetime.now(pytz.utc))
class DataList(APIView):
def post(self, request, format=None):
serializer = DataSerializer(data=request.data)
if serializer.is_valid():
mac_address = request.data['mac_address'].upper()
serializer.save(mac_address=mac_address, datetime=datetime.datetime.utcnow().replace(tzinfo=pytz.utc))
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
And the serialize validator needs to convert to lower case first then query the database.
class DataSerializer(serializers.ModelSerializer):
datetime = ReadOnlyField()
mac_address = CharField(max_length=50,
validators=[UniqueValidator(queryset=Data.objects.all())]
)
def validate_mac_address(self,value):
return value.upper()
Your validator should be doing the actual validation:
class DataSerializer(serializers.ModelSerializer):
datetime = ReadOnlyField()
mac_address = CharField(max_length=50)
def validate_mac_address(self,value):
if Data.objects.filter(mac_address=value.upper()).exists():
raise serializers.ValidationError("MAC address should be unique")
return value.upper()
define valid_email
method into your serializer
class DataSerializer(serializers.ModelSerializer):
email = CharField(
max_length=255,
validators=[UniqueValidator(queryset=BlogPost.objects.all())]
)
// your content and other stuff goes here
def valid_email(self,value):
return value.lower()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With