'how to get a username to show on serializer django rest framework

how would i get the user name to show in the serializer along wit the data. I tried doing serializer char field but did not work.

Model

class Pet(models.Model):
    owner = models.ForeignKey(settings.AUTH_USER_MODEL,
                              null=True, on_delete=models.CASCADE)
    title = models.CharField(max_length=50)

serializer

class PetSerializer(serializers.ModelSerializer):
    class Meta:
        model = Pet
        fields = '__all__'

view set:

class PetViewSet(viewsets.ModelViewSet):
    queryset = Pet.objects.all()
    permission_classes = [
        permissions.AllowAny
        # permissions.IsAuthenticated,
    ]
    serializer_class = PetSerializer

what i tried:

class PetSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
        source = "users.username", read_only = True
    )
    class Meta:
        model = Pet
        fields = '__all__'


expected result:

 {
        "id": 1,
        "title": "dog",
         "owner": 1,
         "username": "someusername"


    },


Solution 1:[1]

username = serializers.CharField(
        source="owner.username", read_only=True)

I needed to get the foreign key, which is owner, and then put username in this serializer.

Solution 2:[2]

You need to add a new field in your serializer by using 'SerializerMethodField'

username = serializers.SerializerMethodField("get_username")

This function will return the username for the serializer:

def get_username(self, obj):
    return obj.owner.username

Solution 3:[3]

class PetSerializer(serializers.ModelSerializer):

    def getUsername(self, obj):
        return obj.user.username

    username = serializers.SerializerMethodField("getUsername")

    class Meta:
        model = Pet
        fields = ('id','username', 'title', 'text', 'created_at', 'update_at')
        read_only_fields = ('id',)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Laurel
Solution 2 sɐunıɔןɐqɐp
Solution 3 Maifee Ul Asad