show list in django without html file

Viewed 41

i have 2 models but i want to show name of artist in my output

class Musician(models.Model):
name = models.CharField(max_length=50)
instrument = models.CharField(max_length=100)

class Album(models.Model):
name = models.CharField(max_length=100)
artist = models.ForeignKey(Musician, on_delete=models.CASCADE)
num_stars = models.IntegerField()

i want to show artist name by HttpResponce funcction

class Musician_list(View):
def get(self, request):
    persons = Album.objects.all().values_list("artist__name").order_by("artist__name")
    return HttpResponse(persons)

but this code dont show any things please help me.

2 Answers

You should JSON serialize this as a list. Furthermore the outer item should be a dictionary, since it turns out using a list as outer item can be unsafe [haacked.com]:

from django.http import JsonResponse

class Musician_list(View):
    def get(self, request):
        persons = list(
            Album.objects.values_list('artist__name', flat=True).order_by('artist__name')
        )
        #        ↓ use a JsonResponse
        return JsonResponse({'data': persons})
        # use a dictionary as outer item ↑

That being said, it is usually better to make use of Django's serialization framework [Django-doc], or for REST frameworks, make use of Django's REST framework [drf-doc].

You Should Change Your QuerySet to list object.

  1. change queryset to list:

person = list(Musician.objects.values_list("name").order_by("name"))

2.If you only pass in a single field, you can also pass in the flat parameter. If True, this will mean the returned results are single values, rather than one-tuples.

person = list(Musician.objects.values_list("name",flat=True).order_by("name"))

or you can do this to retrieve Tuple value that got from queryset:

> person = list(Musician.objects.values_list("name").order_by("name"))  
> out = [item for t in person for item in t]

at least:

> class Musician_list(View):  
>     def get(self, request):  
>       person = list()  
>       person = list(Musician.objects.values_list("name",flat=True).order_by("name"))  
>       return HttpResponse(person,content_type="text/plain")
Related