I'm using Django Rest Framework with django-simple-history and currently I would like to return the history modifications in my Board rest API, currently it is doing well but I would like to hide some fields. This is the currently output:
But, I don't need id, history_id, etc.
my implementation is the same of alexander answer in this post. this is my currently serializers, where I put history on my Board model
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__'
But it does not seem the best way to do it.
If you have some hint about how to do it the correct way I would like to know. Thanks in advance!
CodePudding user response:
You can try this for history_id at least:
def to_representation(self, data):
representation = super().to_representation(data.values())
for hist in representation['history']:
hist.pop('history_id')
return representation
CodePudding user response:
I don't know django-simple-history, so they may be better solutions than mine.
However, you can do this with a more DRF-friendly approach by simply using a ModelSerializer instead of a 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

