first i update my model instance, after that i tried to insert a new data but showing
"IntegrityError(\'duplicate key value violates unique constraint "RFIDActi
In restframework, serializer.save()
has different behavior based on creation and update. If you pass instance to serializer, it will update the object, otherwise, it will create a new one
@api_view(['POST', 'PUT'])
def rfid_data(request, pk):
"""
Update or delete a rfid data.
"""
rfid_activation = {
...
}
if request.method == 'POST':
rfid_serializer = RFIDActivationSerializer(data=rfid_activation)
if rfid_serializer.is_valid():
rfid_serializer.save()
return Response(rfid_serializer.data,status=status.HTTP_201_CREATED)
return return Response(rfid_serializer.data, status=status.HTTP_400_BAD_REQUEST)
# PUT is used for object update
elif request.method == 'PUT':
rfid = RFIDActivation.objects.get(pk=pk)
# pass instance to your serializer
# pass partial=True to allow partial updates
rfid_serializer = RFIDActivationSerializer(instance=rfid, data=rfid_activation, partial=True)
if rfid_serializer.is_valid():
rfid_serializer.save()
return Response(rfid_serializer.data)
return Response(rfid_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
default
is calculated at import time
, in your case, your default value for activation_id
is calculated once and never change for subsequent instances.
You have to define a function, thus default callable will be updated each time on object creation, read more here
def activation_id_generator(self):
return uuid4().hex[:8]
# then in your class
class RFIDActivation(models.Model):
...
ActivationId = models.CharField(max_length=10, unique=True, default=activation_id_generator)