1

I have an example like

[
  {
        "url": "/api/post/12/", 
        "user": "/api/users/1/", 
        "created": "2013-08-06T04:52:28Z", 
        "updated": "2013-08-06T04:52:28Z", 
        "date": "2013-08-06T04:52:28Z", 
        "show": true, 
        "title": "test post", 
        "body": null, 
        "role": "Text", 
        "image_url": "", 
        "image": ""
    }, 
    {
        "url": "/api/post/13/", 
        "user": "/api/users/1/", 
        "created": "2013-08-06T04:53:19Z", 
        "updated": "2013-08-06T04:53:19Z", 
        "date": "2013-08-06T04:53:19Z", 
        "show": true, 
        "title": "test post", 
        "body": null, 
        "role": "Image", 
        "image_url": "http://127.0.0.1:8000/media/photos/photo_1.jpg", 
        "image": "photos/photo_1.jpg"
    }
 ]

I want my HyperlinkedModelSerializer class to not show image_url and image if it's a Text role.

Is this possible?

1 Answer 1

3

You could override to_native in your serializer subclass to strip the unwanted fields in your case.

Something like:

def to_native(self, obj):
    as_native = super(MySerializer, self).to_native(obj)

    # Remove image_url and image fields if Text role.
    if as_native["role"] == "Text":
        as_native.pop('image_url', None)
        as_native.pop('image', None)

    return as_native

I hope that helps.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.