gcman105
gcman105

Reputation: 247

How can transform field names to work with existing API calls in django-rest-framework?

I have a Django app that needs to allow an existing API to make calls to it.

The existing API makes calls like:

/api/product

which expects fields named:

product_id, heading, unit

but the Django app returns fields named:

product_id, title, unit

Is there a way I can keep both ends happy but transforming the names during serialization?

Upvotes: 0

Views: 77

Answers (1)

davyria
davyria

Reputation: 1513

You could create a custom ModelSerializer creating a heading filed name, and setting the source.

class ProductSerializer(serializers.ModelSerializer):

    heading = serializers.CharField(source='title')

    class Meta(object):
        model = Product
        fields = (
            'product_id',
            'heading',
            'unit')

Upvotes: 2

Related Questions