django-rest-framework different fields for serialization -


i have 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 hyperlinkedmodelserializer class not show image_url , image if it's text role.

is possible?

you override to_native in serializer subclass strip unwanted fields in case.

something like:

def to_native(self, obj):     as_native = super(myserializer, self).to_native(obj)      # remove image_url , 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 helps.


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -