pirks pirks - 17 days ago 9
reST (reStructuredText) Question

django rest Serializers how to representation

in django models

class TableFriend(models.Model):
user = models.ForeignKey(User, related_name="main_user", default="newbie")
friend = models.ForeignKey(User, related_name="friend_for_user", default="newbie")
date = models.DateTimeField(auto_now=True)

def __str__(self):
return '%s %s %s' % (self.user, self.friend, self.date)


django rest code

class FriendSerializer(serializers.ModelSerializer):
class Meta:
model = TableFriend
fields = ('user', 'friend', 'date')


output:

[{"user":1,"friend":3,"date":"2016-11-10T15:12:33.189570Z"},{"user":1,"friend":2,"date":"2016-11-10T15:11:56.936230Z"}]


But I need the name of friends.
I want see
"friend":username
.
I want to see also
__str__
from django model.
How can I do it?

Answer

First of all, in your __str__ in TableFriend, you would need to actually pass a string like:

def __str__(self):
    return '%s %s %s' % (self.user.name, self.friend.name, self.date)

I'm assuming you have a name field in the User model.

To display the friend username, you would do:

class FriendSerializer(serializers.ModelSerializer):
    friend_username = serializers.ReadOnlyField(source='friend.username')

    class Meta:
        model = TableFriend
        fields = ('user', 'friend', 'date')

Ref: Specifying read only fields

The output will now be something like:

[{"user":1,"friend":3,"friend_username":"<the_username>","date":"2016-11-10T15:12:33.189570Z"}...]

The __str__ is a string representation of the object. To see it, you would do something like: TableFriend.objects.first(). This would give an output like <TableFriend: my_name friend_name 2016-11-21 23:54:57.060029>

Ref: object.str(self)