7

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)
1
  • What if you query the endpoint with the /<id>/ suffix (with <id> replaced with an id, for example 1, so something like localhost:8000/api/user/1? Commented Jun 14, 2018 at 22:51

1 Answer 1

11

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. Though I ended up using a different solution this did in fact work. I chose the other solution (posted on this thread) as it didn't require additional imports.
@Tantivy Hello, friend. Can you share with me what is the 'other solution'?(If you remember yet XD)
This is a really bad approach especially when the single object that you want to return is specifically the current users user profile... Especially when you want to have some fields non-read only. The idea that you are even exposing the concept of multiple profiles is a security smell.
yes, i said it's not the normal way

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.