I am running into an issue while deserializing JSON data. One of the field is the customerID and i cannot find a way to user a Serializer class properly.
Here is my code:
class UserProfileData(models.Model):
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
captureDateTime = models.CharField(_('Capture datetime'), blank=True, null=True, max_length=100)
class UserProfileDataSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfileData
fields = "__all__"
The JSON i receive is the following:
{ "customerID": "someUUID", "captureDateTime": "..." }
Here is the current state of my view:
@api_view(['POST'])
def register_profile(request):
data = JSONParser().parse(request)
serializer = UserProfileDataSerializer(data=data)
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data, status=201)
return JsonResponse(serializer.errors, status=400)
It fails with the following error:
{'user': [ErrorDetail(string='This field is required.', code='required')]}
I understand i am missing something here, but can't figure out what... Also, i almost forgot to mention the User object has a customerId field. Thanks for your help.
CodePudding user response:
You can pass the source
argument to a field to map it to an attribute with a different name. Something like this should work
class UserProfileDataSerializer(serializers.ModelSerializer):
# May want to use a UUIDField based on your question
# either 'user_id' or 'user' as source
customerID = serializers.CharField(source='user') # 'user'
class Meta:
model = UserProfileData
fields = ('captureDateTime', 'customerID')
CodePudding user response:
Here is the working version:
class UserProfileDataSerializer(serializers.ModelSerializer):
customerId = serializers.SlugRelatedField(source='user', queryset=get_user_model().objects.all(), many=False, slug_field='customerId')
class Meta:
model = UserProfileData
fields = ('captureDateTime', 'customerId')