0

Goal

If an object has revealed=true it serializes into:

{
   "id":1,
   "info":"top secret info",
   "revealed":true
}

If an object has revealed=false the info field is null:

{
   "id":2,
   "info":null,
   "revealed":false
}

So for a queryset of objects:

[  
   {  
      "id":1,
      "info":"top secret info 1",
      "revealed":true
   },
   {
       "id":2,
       "info":null,
       "revealed":false
   },
   {  
      "id":3,
      "info":"top secret info 3",
      "revealed":true
   }
]

Is it possible to achieve this inside of a Django Rest Framework Model Serializer class?

class InfoSerializer(serializers.ModelSerializer):
    class Meta:
        model = Info
        fields = ('id', 'info', 'revealed')

Background

The DRF docs discuss some advanced serializer usage, and this other post dives into an example. However it doesn't seem to cover this particular issue.

Ideas

A hacky solution would be to iterate over the serialized data afterwards, and remove the info field for every object that has revealed=false. However 1) it involves an extra loop and 2) would need to be implemented everywhere the data is serialized.

Peter Tao
  • 1,668
  • 6
  • 18
  • 29

1 Answers1

0

I suggest you make the info field appear on all records, but leave it null when revealed is false. If that's acceptable, you should be able to make it happen with a SerializerMethodField.

Alternatively, you could add a revealed_info attribute to the model class, and expose that through the serializer.

@property
def revealed_info(self):
    return self.info if self.revealed else None
Don Kirkby
  • 53,582
  • 27
  • 205
  • 286