[Answered ]-How do I modify a model field and then send it using the Rest Framework in Python/Django?

2👍

If you are looking to just return this data, this can be done by using a custom SerializerMethodField that will allow you to aggregate all of the data you need, and then pass it back in the API response.

class UserSerializer(serializers.ModelSerializer):
    options = serializers.SerializerMethodField()

    def get_options(self, obj):
        return {
            "something": obj.something,
        }

The other option is to override to_native (DRF 2) / to_representation (DRF 3), but that all depends on where you need to modify the data, and how often you need to do it.

In either situation, you should watch out for N+1 queries that will inevitably come up with dealing with data across foreign keys.


If you are looking to save this custom data automatically, you can do it by overriding the perform_create and perform_update hooks on the view.

Leave a comment