【问题标题】:How to get username of user's post in Django REST API instead of number?如何在 Django REST API 中获取用户帖子的用户名而不是数字?
【发布时间】:2019-09-27 02:44:58
【问题描述】:

我正在尝试通过 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)

我希望 "author": 1, 就像 "author": admin,.

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    您可以使用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】:

      您需要将您的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', )
      

      【讨论】:

        【解决方案3】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-01-12
          • 1970-01-01
          • 2016-08-10
          • 2021-01-14
          • 1970-01-01
          • 2019-04-04
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多