OneBite.Dev - Coding blog in a bite size

Different column name on using ModelSerializer in Django Rest Framework

How to solve different column name upon using ModelSerializer and Class Meta in Django Rest Framework

If the data you pass from the views doesn’t match the column names in your model (which is what Django’s ModelSerializer is based on), you have a couple of options:

Opt. 1 Renaming fields in the serializer

You can override fields in the ModelSerializer to match the data from your view. For example, if your model has a field called `field1`, but your data uses `inputField1` instead, you could do:

class YourSerializer(serializers.ModelSerializer):
  inputField1 = serializers.CharField(source = 'field1')

  class Meta:
    model = YourModel
    fields = ('inputField1', ...)

In this case, the `source` argument tells the serializer to use the `field1` attribute from the model but to expose it under the name `inputField1`.

Opt 2. Transform data in the view

Alternatively, you could transform the data in the view before passing it to the serializer, so that it matches the model field names.

def post(self, request, format=None):
    data = request.data.copy()  # make a mutable copy
    data['field1'] = data.pop('inputField1')  # rename fields

    serializer = YourSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

Both approaches have their uses. Overriding fields in the serializer is more flexible and reusable, but it can add complexity if you’re dealing with a lot of fields or complex nested relationships. Transforming the data in the view is simpler and might make more sense if the mismatch is due to the way the client sends the data (e.g., if you’re dealing with a third-party API that you can’t control).

django-rest-framework