1

我有一个例子

[
  {
        "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 和 image。

这可能吗?

4

1 回答 1

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

我希望这会有所帮助。

于 2013-08-08T06:27:14.887 回答