1

Hello I need to modify some data before the rest framework sends it to a client. The data being sent is from a model object.

Here's a code example of my model.

class UserOptions(models.Model):
    options = models.TextField(null=False, null=True)

Now when the client requests a specific users options I need to modify options by adding a combination of elements from 2-3 other models into a big JSON String. How can I accomplish this, I assume through a Serializer but I'm not sure how to specifically modify a requested field accordingly.

Ricky
  • 823
  • 2
  • 14
  • 31
  • Check out the `to_native` method of the serializers. – dursk Jan 12 '15 at 19:52
  • Do you mean that you want to modify the response for one field? With http://www.django-rest-framework.org/api-guide/fields/#serializermethodfield you can run custom code and return modified content for that field. You can also use it to add additional arbitrary fields that have access to the model instance to compute a needed output. – sthzg Jan 12 '15 at 20:52

1 Answers1

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.

Community
  • 1
  • 1
Kevin Brown-Silva
  • 40,873
  • 40
  • 203
  • 237