1

With the below model and serializer:

class Person(models.Model):
    name = models.CharField(max_length=30)


class PersonSerializer(serializers.Serializer):

    class Meta:
        model = User
        fields = ('name',)

I get:

[
   {"name": "Jon"},
   {"name": "Joe"},
   {"name": "Jim"}
]

How can I customize the serializer so that it outputs something like this:

{
  "out": [
    {"name": "Jon"},
    {"name": "Joe"},
    {"name": "Jim"}
  ],
  "message": "success"
}

Here message is built at runtime, otherwise I could have hard-coded it in JSONRenderer.

1
  • You should write custom Renderer class. Look Custom renderers here Commented Nov 27, 2014 at 22:07

1 Answer 1

1

You haven't really specified what type of control do you need over this message or where you want to be able to define it (on the serializer level, view level?).

You can always override the dispatch method like this (MySimpleView view class):

def dispatch(self, request, *args, **kwargs):
    response = super(MySimpleView, self).dispatch(request, *args, **kwargs)

    data = {}
    data['out'] = response.data
    data['message'] = "My message"

    response.data = data

    return response

I assume you want to control your custom message depending on the response status, so this seems like a perfect place, since the dispatch method returns the response itself.

So now just make it into a nice mixin and reuse it in you views..

But if you don't need the response status, then custom renderer is the way to go.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.