Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a single object with Django-Rest-Framework

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)
like image 497
Tantivy Avatar asked Jun 14 '18 22:06

Tantivy


People also ask

What does Django objects get return?

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.

What is renderers in Django REST framework?

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.

What is Restapi in Django?

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.

What is HyperlinkedModelSerializer in 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.


1 Answers

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)
like image 153
Ykh Avatar answered Oct 06 '22 01:10

Ykh