I'm trying to return a single object with profile information but am stuck getting an array in return. How do I just return a single object.
Current output:
[{"id":1,"username":"someusername"}]
Desired output:
{"id":1,"username":"someusername"}
serializers.py
from rest_framework import serializers
from django.contrib.auth.models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'username')
views.py
# from django.shortcuts import render
from django.contrib.auth.models import User
from profiles.serializers import UserSerializer
from rest_framework import viewsets
# Create your views here.
class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet):
"""
Lists information related to the current user.
"""
serializer_class = UserSerializer
def get_queryset(self):
user = self.request.user.id
return User.objects.filter(id=user)
It would return the object of your model on which you are querying. If nothing matches and no rows is returned, it would through a Model.
The rendering process takes the intermediate representation of template and context, and turns it into the final byte stream that can be served to the client. REST framework includes a number of built in Renderer classes, that allow you to return responses with various media types.
Django REST framework (DRF) is a powerful and flexible toolkit for building Web APIs. Its main benefit is that it makes serialization much easier. Django REST framework is based on Django's class-based views, so it's an excellent option if you're familiar with Django.
HyperlinkedModelSerializer is a layer of abstraction over the default serializer that allows to quickly create a serializer for a model in Django. Django REST Framework is a wrapper over default Django Framework, basically used to create APIs of various kinds.
The normal usage is use /user/
to get a list,use /user/[user_id]/
to get a certain object.
If you want /user/
return detail info,do as:
class CurrentUserViewSet(viewsets.ReadOnlyModelViewSet):
"""
Lists information related to the current user.
"""
serializer_class = UserSerializer
permission_classes = (IsAuthenticated,)
def list(self, request, *args, **kwargs):
instance = request.user
serializer = self.get_serializer(instance)
return Response(serializer.data)
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