[Django]-Using reverse relationships with django-rest-framework's serializer

9πŸ‘

βœ…

Serializer makes a database query (not a join, but a separate query)
for each user, to get his/her name.

You can use select_related() on the queryset attribute of your view. Then accessing user.name will not result in further database queries.

class CommentsList(generics.ListAPIView):
    serializer_class = CommentListItemSerializer
    queryset = Comment.objects.all().select_related('user') # use select_related

I don’t want to have this nested object "user.name". I’d like to
receive that as a simple string field, for example "username"

You can define a read-only username field in your serializer with source argument. This will return a username field in response.

class CommentListItemSerializer(serializers.ModelSerializer):
    # define read-only username field
    username = serializers.CharField(source='user.name', read_only=True) 

    class Meta:
        model = Comment
        fields = ('username', 'contents', 'rating')
πŸ‘€Rahul Gupta

3πŸ‘

You can add custom functions as fields

class Comment(models.Model):
    user = models.ForeignKey(User, on_delete=models.PROTECT, blank=True, null=True)
    contents = models.CharField(max_length=510)
    rating = models.IntegerField(blank=False, null=False)

    def username(self):
        return self.user.name


class CommentListItemSerializer(serializers.ModelSerializer):

    class Meta:
        model = Comment
        fields = ('username', 'contents', 'rating')
πŸ‘€Jose Maeso

Leave a comment