Hiding the IDs

The API looks great, except for the security risk of exposing the user model's primary key publicly. Thankfully, the serializers can be changed to add fields that are not present in the model, as the following code demonstrates:

class PostSerializer(serializers.ModelSerializer): 
    posted_by = serializers.SerializerMethodField() 
 
    def get_posted_by(self, obj): 
        return obj.posted_by.username 
 
    class Meta: 
        model = models.Post 
        fields = ("posted_by", "message",) 

The SerializerMethodField is a read-only field that gets its value from a class method. By default, this is the method named get_<field_name>.

Now, the API returns posts with the usernames instead of the user's primary key, as the following screenshot shows:

If you are a REST ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.