Jessica Chambers
Jessica Chambers

Reputation: 1316

Django: How to not return all model fields

I'm using a Django system where each model has an associated serializer (pretty standard).

In one model, the serializer is as follows:

class ThingSerializer(ModelSerializerWithFields):
    class Meta:
        model = Thing
        fields = "__all__"

and a model:

class Thing(models.Model):
    class Meta:
        ordering = ("a", "b")


    thing_id = models.UUIDField(primary_key=True, default=uuid.uuid4, blank=True, editable=False)
    a = models.FloatField(null=True, blank=True, default=None)
    b = models.FloatField(null=True, blank=True, default=None)

I want to implement a system that: if field a of Thing is not null, then field b is returned (on a GET request, for example), and if a is null then b is not returned. How (and where) can I do this?

Upvotes: 0

Views: 344

Answers (1)

Danilo Akamine
Danilo Akamine

Reputation: 765

You could override to_representation() method on your serializer. Like this:

class ThingSerializer(serializers.ModelSerializer):
    ...

    def to_representation(self, instance):
        data = super().to_representation(instance)
        if instance.a is None:
            del data['b']
        return data

Upvotes: 1

Related Questions