Reputation: 11
I'm trying to get username for iOS app through REST API. I could get user number. How do I get actual username?
The "author" should be username of user post.
http://127.0.0.1:8000/api/posts/
Result
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"author": 1,
"title": "Test Title Post",
"contents": "Test contents post"
}
User = settings.AUTH_USER_MODEL
class PostDetail(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="PostDetail.author+")
title = models.CharField('*Title', max_length=50)
contents = models.TextField('*Contents', max_length=450)
from rest_framework import serializers
from .models import PostDetail
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
class PostDetailSerializer(serializers.ModelSerializer):
class Meta:
model =PostDetail
fields = (author, title, 'contents', )
from rest_framework import viewsets, routers
from blog.models import PostDetail
from blog.serializer import PostDetailSerializer
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
class PostViewSet(viewsets.ModelViewSet):
queryset = PostDetail.objects.all()
serializer_class = PostDetailSerializer
router = routers.DefaultRouter()
router.register(r'posts', PostViewSet)
I expect "author": 1, to be like "author": admin,.
Upvotes: 1
Views: 3448
Reputation: 3156
if you have to use for input value to, you can create the custom serializer fields
class ForeignKeyField(serializers.RelatedFields):
def to_representation(self, obj):
return obj.name
this fields can be use in the serializer
class PostDetailSerializer(serializers.ModelSerializer):
author = ForeignKeyField()
class Meta:
model =PostDetail
fields = (author, title, 'contents', )
Upvotes: 0
Reputation: 8077
You need to change your PostDetailSerializer
to:
from rest_framework import serializers
from .models import PostDetail
from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
class PostDetailSerializer(serializers.ModelSerializer):
author = serializers.CharField(source='author.username', read_only=True)
class Meta:
model =PostDetail
fields = (author, title, 'contents', )
Upvotes: 5
Reputation: 1810
You can use SerializerMethodField
for this task. You need to define a function to get the username of the author.
This is how you do it:
class PostDetailSerializer(serializers.ModelSerializer):
author = serializers.SerializerMethodField()
class Meta:
model =PostDetail
fields = (author, title, 'contents', )
def get_author(self, obj):
return obj.author.username
The function should be named as get_<field_name>
.
Upvotes: 1