[Fixed]-Dump A Custom Filtered Field as Response in Django Rest Framework

1πŸ‘

βœ…

It’s pretty simple – use the source core argument of DRF.

Step 1

Define on your Tag model a method that computes the number of occurrences of any tag:

class Tag(models.Model):
    label = models.SlugField(null=False, blank=False, unique=True)

    def nr_of_entries(self):
        return self.entry_set.count()

Step 2

Then on your TagSerializer add a custom field that will take its data from the method you defined above:

class TagSerializer(serializers.ModelSerializer):
    length = serializers.IntegerField(source="nr_of_entries", read_only=True)
    class Meta:
        model = Tag
        fields = ("label", "length")

Now, when an instance of a tag will be serialized, it will contain a length property that will take its value from the result of running the nr_of_entries method on that tag instance.

πŸ‘€iulian

Leave a comment