Fields that differ between model and serializer (Django Rest Framework)

Hi :wave:

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

  1. I receive a POST request from the frontend with the fields in camelCase
{
    "authorId": 14,
    "authorName": "Stephen King"
}
  1. I serialize the data
serializer = BookSerializer(data=request.data)
  1. 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()
  1. (Extra) Sometimes I may need to return the Book model saved.
    Is there a way to make the conversion authorId => 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!

There’s probably other options - you could name your fields to match what’s being received:

class Book(Model):
    authorId = ...
    authorName = ...

or, you may be able to use the source attribute on your field definition.

Renaming the model fields is the most obvious solution, I will not discard it.
Just wanted to keep the project Djangonic.

On the other hand, should I use the source attribute like this?

class BookSerializer(serializers.ModelSerializer):
    author_id = serializers.IntegerField(source="authorId")
    author_name = serializers.CharField(source="authorName")

    class Meta:
          model = Book
          fields = ["authorId", "authorName"]

That way the model fields will get their value from the request fields.

Not really sure right now but tomorrow I’ll try this approach.

Thanks Ken.