1

我正在使用带有 django-simple-history 的 Django Rest Framework,目前我想在我的Boardrest API 中返回历史修改,目前它做得很好,但我想隐藏一些字段。这是当前的输出:

在此处输入图像描述

但是,我不需要id,history_id等。

我的实现与本文中的亚历山大回答相同。这是我目前的序列化程序,我将历史记录放在我的 Board 模型上

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__'

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

如果您对如何以正确的方式进行操作有一些提示,我想知道。提前致谢!

4

2 回答 2

0

我不知道django-simple-history,所以他们可能是比我更好的解决方案。但是,您可以通过简单地使用ModelSerializer而不是ListSerializer
来使用对 DRF 更友好的方法来做到这一点:

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 重命名为“历史”):

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

请记住,我对这个库了解不多,所以这应该可以工作,但我不能保证它是最好的方法。

于 2022-01-05T14:52:46.247 回答
0

history_id你至少可以试试这个:

def to_representation(self, data):
        representation = super().to_representation(data.values())
        for hist in representation['history']:
            hist.pop('history_id')
        return representation
于 2022-01-05T14:46:41.380 回答