Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
Tantivy Avatar asked Jun 11 '18 20:06

Tantivy


People also ask

What is serialization in Django REST Framework?

Serializers in Django REST Framework are responsible for converting objects into data types understandable by javascript and front-end frameworks. Serializers also provide deserialization, allowing parsed data to be converted back into complex types, after first validating the incoming data.

How do I serialize Queryset?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

Is serialization necessary in Django?

It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.


Video Answer


1 Answers

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

like image 182
Tantivy Avatar answered Oct 08 '22 10:10

Tantivy