Reputation: 606
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)
Upvotes: 7
Views: 7371
Reputation: 7717
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)
Upvotes: 11