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.
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.
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.
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.
Solved. Was a typo. In serializers.py the class should be using "serializers.ModelSerializer" and not "serializers.Serializer".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With