My question was: How can I improve this detailed view of a contributor?
# serializers.py
class ContributorDetailSerializer(serializers.ModelSerializer):
    class Meta:
        model = Contributor
        fields = ["id", "user"]
result in Postman:
My contributor model has just one attribute: user a ForeignKey relation to the user model.
# models.py
class User(AbstractUser):
    pass
    def __str__(self):
        return self.username
class Contributor(models.Model):
    user = models.ForeignKey(
        "api.User",
        on_delete=models.CASCADE,
        related_name="users",
        verbose_name=_("user"),
    )
    def __str__(self):
        return self.user.username
There are several possibilities, I want to show two different approaches:
first example:
using the __str__ method of the user model
# serializers.py
class ContributorDetailSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField()
    class Meta:
        model = Contributor
        fields = ["id", "user"]
result in Postman:
user = serializers.StringRelatedField() is displaying the __str__ method of the user model. As you can see above in the __str__ method in user model, it returns the username of the user.
second example
display all information of an other Serializer
# serializers.py
class ContributorDetailSerializer(serializers.ModelSerializer):
    user = UserSerializer(read_only=True)
    class Meta:
        model = Contributor
        fields = ["id", "user"]
user = UserSerializer(read_only=True) takes all the attributes of UserSerializer and adds them to the ContributorSerializer attribute user and display all information. 
 




 
    
Top comments (0)