How to serialize tthe foreign key field in django rest framework

I working on project with drf where I'm getting serializer data as follows which is absolutely fine:

{
    "message": "Updated Successfully",
    "status": 200,
    "errors": {},
    "data": {
        "id": 8,
        "user": 2,
        "item": 1,
        "quantity": 4,
        "created_at": "2021-08-11T13:49:27.391939Z",
        "updated_at": "2021-08-11T13:51:07.229794Z"
    }
}

but I want to get as following:

{
    "message": "Updated Successfully",
    "status": 200,
    "errors": {},
    "data": {
        "id": 8,
        "user": "user name",
        "item": "product name",
        "price: "3.44",
        "quantity": 4,
        "created_at": "2021-08-11T13:49:27.391939Z",
        "updated_at": "2021-08-11T13:51:07.229794Z"
    }
}

I tried using drf RelatedField and PrimaryKryRelatedField but in all these cases I need to make corresponding fields as read_only=True which I want to skip.

I also tried with depth = 1 which gives entire details

Please if anyone can help, it would be greatly appreciated. Thanks

You can make use of to_representation()

Give this a try

class CartSerializer(serializers.ModelSerializer):

    class Meta:
        model = Cart

    def to_representation(self, instance):
        representation = dict()
        representation["id"] = instance.id
        representation["user"] = instance.user.username
        representation["item"] = instance.item.name
        representation["quantity"] = instance.quantity
        representation["created_at"] = instance.created_at
        representation["updated_at"] = instance.updated_at

        return representation

NB: You may have to change instance.field_name(s) accordingly

Back to Top