December 2018
Beginner to intermediate
796 pages
19h 54m
English
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 ...
Read now
Unlock full access