【问题标题】:Django serializer field value base on other field in the same serializerDjango 序列化程序字段值基于同一序列化程序中的其他字段
【发布时间】:2015-03-27 07:03:38
【问题描述】:

假设我有以下序列化程序。

class ArticleSerializer(serializers.ModelSerializer):    
    comment_count = serializers.SerializerMethodField()
    commented = serializers.SerializerMethodField()
    def get_comment_count(self, obj):
        # Assume the method can retrieve the comment count correctly
        return x
    def get_commented(self, obj):
        # Return True if comment count > 0, else False
    class Meta:
        model = Article
        fields = ['title', 'content', 'comment_count', 'commented']

get_commented 方法中的编码有什么建议吗?我编写了类似return comment_count > 0 的代码但失败了。

【问题讨论】:

  • 怎么样:return self.get_comment_count(obj) > 0?

标签: python django serialization django-rest-framework


【解决方案1】:

您可以使用 obj 访问 django 对象,所以我认为代码将类似于:

obj.comment_set.count()

获取评论数,然后:

return self.get_comment_count(obj) > 0

正如 Pang 所说的实现 get_commented

【讨论】:

    猜你喜欢
    • 2021-11-08
    • 2014-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-28
    • 2022-12-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多