首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从django中排除历史字段-- django rest框架中to_representation方法的简单历史

从django中排除历史字段-- django rest框架中to_representation方法的简单历史
EN

Stack Overflow用户
提问于 2022-01-05 14:17:23
回答 2查看 293关注 0票数 1

我将Django Rest框架与django-简单历史一起使用,目前我想在我的Board rest中返回历史修改,目前它做得很好,但是我想隐藏一些字段。这是当前的输出:

但是,我不需要idhistory_id等。

我的实现与亚历山大在这个帖子中的答案是一样的。这是我当前的序列化程序,我将历史记录放在我的板模型中

代码语言:javascript
复制
class HistoricalRecordField(serializers.ListField):
    child = serializers.DictField()

    def to_representation(self, data):
        representation = super().to_representation(data.values())
        # i've tried to do it by deleting, but does't work well.
        del representation[0]['history_id']
        return representation


class BoardSerializer(serializers.ModelSerializer):
    history = HistoricalRecordField(read_only=True)

    class Meta:
        model = Board
        fields = '__all__'

但这似乎不是最好的方法。

如果你对如何正确地做这件事有一些提示的话,我想知道。提前感谢!

EN

回答 2

Stack Overflow用户

发布于 2022-01-05 14:46:41

您至少可以为history_id尝试这样的方法:

代码语言:javascript
复制
def to_representation(self, data):
        representation = super().to_representation(data.values())
        for hist in representation['history']:
            hist.pop('history_id')
        return representation
票数 0
EN

Stack Overflow用户

发布于 2022-01-05 14:52:46

我不知道django-simple-history,所以它们可能是比我的更好的解决方案。

但是,您可以使用一种更适合DRF的方法来完成这一任务,只需使用ModelSerializer而不是ListSerializer

代码语言:javascript
复制
class HistoricalRecordSerializer(serializers.ModelSerializer):

    class Meta:
        model = HistoricalRecords
        fields = ('name', 'description', 'share_with_company', [...]) # Only keep the fields you want to display here


class BoardSerializer(serializers.ModelSerializer):
    history = HistoricalRecordSerializer(read_only=True, many=True)

    class Meta:
        model = Board
        fields = ('name', 'description', 'history', [...]) # Only keep the fields you want to display here

如果只想检索最新更新,可以使用SerializerMethodField (文档这里)。请记住在Meta.fields中声明它而不是“历史记录”(如果要保留此名称,请将您的SerializerMethodField重新命名为“历史记录”):

代码语言:javascript
复制
class HistoricalRecordSerializer(serializers.ModelSerializer):

    class Meta:
        model = HistoricalRecords
        fields = ('name', 'description', 'share_with_company', [...]) # Only keep the fields you want to display here


class BoardSerializer(serializers.ModelSerializer):
    latest_history = serializers.SerializerMethodField()

    def get_latest_history(self, instance):
        latest_history = instance.history.most_recent()  # Retrieve the record you want here
        return HistoricalRecordSerializer(latest_history).data

    class Meta:
        model = Board
        fields = ('name', 'description', 'latest_history', [...]) # Only keep the fields you want to display here

请记住,我对这个库不太了解,所以这应该有效,但我不能保证这是实现这个库的最佳方法。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70594408

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档