【发布时间】: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