django-rest-framework用于序列化的不同字段

时间:2013-08-08 05:02:26

标签: django django-rest-framework

我有一个像

这样的例子
[
  {
        "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"
    }
 ]

我希望我的HyperlinkedModelSerializer课程不显示image_url和图片,如果它是文字角色。

这可能吗?

1 个答案:

答案 0 :(得分:3)

您可以覆盖序列化程序子类中的to_native以删除案例中不需要的字段。

类似的东西:

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

我希望有所帮助。