【问题标题】:Serializing differently depending on the data in django rest frame work根据 django rest 框架中的数据进行不同的序列化
【发布时间】:2019-05-19 15:41:14
【问题描述】:

我在序列化对象时遇到了一些麻烦,具体取决于它的数据。

我想将帖子数据返回给客户端,其中包括“标题”、“内容”、“作者”、“is_anonymous”等信息。

这就是问题所在。 当我收到一个需要数据的请求时,'is_anonymous' 字段为 'true',我不应该提供 'author' 字段。

我尝试在 ViewSet 中自定义 'list' 或 'receive' 方法,但即使我将 'anonymous' 和非匿名的分类,它仍然通过相同的序列化程序。所以,我得出结论,这是关于序列化程序,而不是视图集。

我该怎么办?

【问题讨论】:

  • 据我所知,DRF 并没有真正设置为提供具有不同结构的资源列表(即,不包括某些对象的字段,但不包括其他对象)。将匿名的author 字段更改为null 或像"Anonymous" 这样的硬编码就足够了吗?

标签: django-rest-framework


【解决方案1】:

您可以查看重写序列化程序的to_representation() 方法。这是我的意思的一个简单示例。

class ExampleSerializer(serializers.ModelSerializer):

    def to_representation(self, instance):
        rep = super().to_representation(instance)
        if instance.is_anonymous:
            rep["author"] = None
            # del rep["author"]
        return rep

这里我调用的是常规的to_representation()方法,然后根据is_anonymous属性修改结果。 You may want to familiarise yourself with the implementation of to_representation(instance)

【讨论】:

    猜你喜欢
    • 2016-03-23
    • 2017-11-24
    • 2015-04-12
    • 2021-11-02
    • 1970-01-01
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多