pirks pirks - 4 months ago 37
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')



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


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:


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)