DEV Community

DoriDoro
DoriDoro

Posted on

DRF detailed information of user in related serializer

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"]
Enter fullscreen mode Exit fullscreen mode

result in Postman:

postman result


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
Enter fullscreen mode Exit fullscreen mode

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"]
Enter fullscreen mode Exit fullscreen mode

result in Postman:

username displayed

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"]
Enter fullscreen mode Exit fullscreen mode

result in Postman:
all info of user model

user = UserSerializer(read_only=True) takes all the attributes of UserSerializer and adds them to the ContributorSerializer attribute user and display all information.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more