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

但是,我不需要id,history_id等。
我的实现与亚历山大在这个帖子中的答案是一样的。这是我当前的序列化程序,我将历史记录放在我的板模型中
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__'但这似乎不是最好的方法。
如果你对如何正确地做这件事有一些提示的话,我想知道。提前感谢!
发布于 2022-01-05 14:46:41
您至少可以为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-05 14:52:46
我不知道django-simple-history,所以它们可能是比我的更好的解决方案。
但是,您可以使用一种更适合DRF的方法来完成这一任务,只需使用ModelSerializer而不是ListSerializer。
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请记住,我对这个库不太了解,所以这应该有效,但我不能保证这是实现这个库的最佳方法。
https://stackoverflow.com/questions/70594408
复制相似问题