如何在Django REST API中获取用户帖子的用户名而不是数字?

时间:2019-05-09 09:33:43

标签: django django-rest-framework

我正在尝试通过REST API获取iOS应用的用户名。 我可以获取用户号码。 如何获得实际的用户名?

“作者”应为用户帖子的用户名。

http://127.0.0.1:8000/api/posts/

结果

HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept

[
    {
        "author": 1,
        "title": "Test Title Post",
        "contents": "Test contents post"
  }

models.py

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)

serializer.py

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', )

apis.py

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)

我希望“作者”:1像“作者”:admin一样。

3 个答案:

答案 0 :(得分:1)

您需要将PostDetailSerializer更改为:

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', )

答案 1 :(得分:0)

您可以使用SerializerMethodField来完成此任务。您需要定义一个函数来获取作者的用户名。

这是您的操作方式:

class PostDetailSerializer(serializers.ModelSerializer):
    author = serializers.SerializerMethodField()
    class Meta:
        model =PostDetail
        fields = (author, title, 'contents', )

    def get_author(self, obj):
        return obj.author.username

该函数应命名为get_<field_name>

答案 2 :(得分:0)

如果必须用于输入值,则可以创建自定义序列化器字段

class ForeignKeyField(serializers.RelatedFields):

    def to_representation(self, obj):
        return obj.name

此字段可以在序列化程序中使用

class PostDetailSerializer(serializers.ModelSerializer):

   author = ForeignKeyField()

   class Meta:
       model =PostDetail
       fields = (author, title, 'contents', )