如何在Django Rest Framework中序列化用户模型

时间:2018-06-11 20:12:41

标签: python django django-rest-framework

我试图熟悉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教程的样板。

我得到的结果是每个用户的空白对象。如果我添加/删除用户,空格的数量会增加和缩小,这告诉我,我至少部分地连接到用户模型。示例如下:

[{},{},{}]

我期待的是:

[{"username": "jimjones", "email": "jim&jones.com", "id": 0},{...}]

任何帮助表示感谢。

1 个答案:

答案 0 :(得分:0)

解决。是一个错字。在serializers.py中,类应该使用“serializers.ModelSerializer”而不是“serializers.Serializer”。