我正在尝试使自己熟悉Django Rest Framework。尝试进行实验以列出我创建的用户,但序列化程序始终返回空白对象。这是我的代码:
serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
class CurrentUserSerializer(serializers.Serializer):
class Meta:
model = User
fields = ('username', 'email', 'id')
urls.py
from django.urls import include, path
from administration import views
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register(r'admin', views.CurrentUserViewSet)
urlpatterns = [
path('', include(router.urls)),
]
views.py
from django.shortcuts import render
from django.contrib.auth.models import User
from administration.serializers import CurrentUserSerializer
from rest_framework import viewsets
# Create your views here.
class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet):
queryset = User.objects.all()
serializer_class = CurrentUserSerializer
其余代码几乎是基于DRF教程的样板。
我得到的结果是每个用户的空白对象。如果我添加/删除用户,则空白的数量会增加和减少,这表明我至少部分地依赖于User模型。下面的例子:
[{},{},{}]
我期望的是这样的:
[{"username": "jimjones", "email": "jim&jones.com", "id": 0},{...}]
任何帮助表示赞赏。
最佳答案
解决了。是一个错字。在serializers.py中,该类应使用“serializers.ModelSerializer”而不是“serializers.Serializer”。