Expecting JSON object instead of JSON Array

373 views
Skip to first unread message

Salah Abdul Gafoor

unread,
Apr 21, 2020, 9:04:15 AM4/21/20
to Django users
In my django application with database engine djongo, I'm trying to return a JSON response by retrieving from my database. But, I'm receiving JSON array instead of JSON object. Currently, there is only one record in my database. Please see the code below.

model.py

class bloodDonors(models.Model):
location
=models.CharField(max_length=20)
name
=models.CharField(max_length=20)
phone
=models.IntegerField()
address
=models.TextField()
bloodGroup
=models.CharField(max_length=5)
type
=models.CharField(max_length=20)
def __str__(self):
   
return self.name


views.py

class bloodDonersView(viewsets.ModelViewSet):
    queryset
= bloodDonors.objects.all()
    serializer_class
= bloodDonorsSerializer


JSON Reponse:

[
   
{
       
"id": 3,
       
"location": "Delhi",
       
"name": "Tony",
       
"phone": 888,
       
"address": "South street",
       
"bloodGroup": "B+",
       
"type": "blood-donation"
   
}
]

But, actually I needed the response as given below:

{
   
"id": 3,
   
"location": "Delhi",
   
"name": "Tony",
   
"phone": 888,
   
"address": "South street",
   
"bloodGroup": "B+",
   
"type": "blood-donation"
}

Salah Abdul Gafoor

unread,
Apr 21, 2020, 9:04:20 AM4/21/20
to Django users
In my django application with database engine djongo, I'm trying to return a JSON response by retrieving from my database. But, I'm receiving JSON array instead of JSON object. Currently, there is only one record in my database. Please see the code below.

model.py

class bloodDonors(models.Model):
location
=models.CharField(max_length=20)
name
=models.CharField(max_length=20)
phone
=models.IntegerField()
address
=models.TextField()
bloodGroup
=models.CharField(max_length=5)
type
=models.CharField(max_length=20)
def __str__(self):
   
return self.name

views.py

class bloodDonersView(viewsets.ModelViewSet):
    queryset
= bloodDonors.objects.all()
    serializer_class
= bloodDonorsSerializer


JSON Reponse I got:

Andréas Kühne

unread,
Apr 22, 2020, 4:25:55 AM4/22/20
to django...@googlegroups.com
You are doing a get to the default route for the viewset I am guessing? That would return a list - because you are getting ALL records and not one specific record.

If you added more records to the database you will also see more in the list.

See here for more information:
https://www.django-rest-framework.org/api-guide/viewsets/

Regards,

Andréas


--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/5656271c-fe21-4933-ad3f-9dc7505a56c1%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages