Tantivy
Tantivy

Reputation: 606

How do you Serialize the User model in Django Rest Framework

Am trying to familiarize myself with the Django Rest Framework. Tried an experiment to list the users I created but the serializer always returns blank objects. Here's my code:

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

Rest of the code is pretty much boilerplate based on the DRF tutorial.

The result I'm getting is blank objects for every user. The number of blanks grows and shrinks if I add/remove a user, which tells me I'm at least partially hooked up to the User model. Example below:

[{},{},{}]

What I'm expecting is something like:

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

Any help appreciated.

Upvotes: 21

Views: 26511

Answers (1)

Tantivy
Tantivy

Reputation: 606

Solved. Was a typo. In serializers.py the class should be using "serializers.ModelSerializer" and not "serializers.Serializer".

Upvotes: 21

Related Questions