Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return single object in django GET api (rest framework)

I have a Table "Configuration".

class Configuration(models.Model):
    inventory_check = models.BooleanField(default=False)
    refund = models.BooleanField(default=False)
    record_seat_number = models.BooleanField(default=False)
    base_url = models.URLField()

This table will have a single entry. Below is the serializer :

class ConfigurationSerializer(serializers.ModelSerializer):
    class Meta:
        model = Configuration
        fields = '__all__'

I am using rest framework for the API. Below is the Views.py

@api_view(['GET'])
def get_configuration(request):
     m = Configuration.objects.all()
     serializer = ConfigurationSerializer(m, many=True)
     return Response(serializer.data, status=status.HTTP_200_OK)

This works perfectly. But the problem is this would return object inside array.

[
{
    "id": 1,
    "inventory_check": false,
    "refund": true,
    "record_seat_number": false,
    "base_url": "http://localhost:8000/"
}
]

All I want is to send only the object without array. How to achieve this?

like image 863
madhuri H R Avatar asked May 10 '17 09:05

madhuri H R


2 Answers

 m = Configuration.objects.get(id=1) # you need to get single object here
 serializer = ConfigurationSerializer(m) # remove many = True
like image 187
aliva Avatar answered Nov 11 '22 23:11

aliva


Simply remove the many=True from the serializer instantiation:

 serializer = ConfigurationSerializer(m)
like image 25
Linovia Avatar answered Nov 11 '22 22:11

Linovia