Hi
For context, I’m migrating a project to Django with DRF.
I can’t modify the frontend so I need to adapt what I receive to make it work with Django.
(This is an example for simplicity, I know that author could be a FK.)
class Book(models.Model):
author_id = ... # This is the recommended way to define fields in Django
author_name = ...
class BookSerializer(serializers.ModelSerializer):
authorId = serializers.IntegerField()
authorName = serializers.IntegerField()
class Meta:
model = Book
Problem
- I receive a POST request from the frontend with the fields in camelCase
{
"authorId": 14,
"authorName": "Stephen King"
}
- I serialize the data
serializer = BookSerializer(data=request.data)
- Then if I want to save it an error is thrown because these fields doesn’t exist on the model.
if serializer.is_valid():
serializer.save()
- (Extra) Sometimes I may need to return the Book model saved.
Is there a way to make the conversionauthorId
=>author_id
=>authorId
that’s not via creating dicts manually?**
Approachs
- Modify the serializer
create
method. - Use the Model serializer as is and map manually the request data to what the serializer expects.
- User
to_internal_value
(Not sure about this)
I think this problem falls into the category of serializer patterns. Would appreciate to find some resources or projects to look at.
Thanks!