Home > Back-end >  how to return queryset as a list on seperate lines, without the brackets
how to return queryset as a list on seperate lines, without the brackets

Time:09-21

I have my model for my lessons:

class Lessons(models.Model):
student = models.ForeignKey(Students, 
on_delete=models.SET_NULL, null=True) 

headed_by = models.ForeignKey(Tutors, 
on_delete=models.SET_NULL, null=True)
day = models.CharField(max_length=4, 

choices=DAY_CHOICES, null=True)

start_time = models.TimeField(null=True, 
 blank=True)

type  = models.CharField(max_length=7, 
choices=TYPE_CHOICES, null=True)

price_band  = models.CharField(max_length=7, 
choices=PAYMENT_TYPE_CHOICES, blank=True, null=True)

created  = models.DateTimeField(auto_now_add=True )


def __str__(self):
    return str(self.student)   " at "   
str(self.start_time)  " on "   str(self.day)
class Meta:
    ordering=['student',"headed_by",'day','start_time']  

I have my Query set:

tn_mon     = 
Lessons.objects.all().filter(headed_by__name="Tutor 
Name").filter(day__icontains="Mon")

which returns

<QuerySet [<Lessons:Studentname1 at Time on Day>,
<Lessons:Studentname2 at Time on Day>

how can i return the output without the queryset, ,<> [] so that it returns as set out like below?

Studentname1 at Time on Day,
Studentname2 at Time on Day

CodePudding user response:

tn_mon = Lessons.objects.all().filter(headed_by__name="Tutor 
Name").filter(day__icontains="Mon").values()

#convert this object it into list
my_list = list(tn_mon)

#If you iterate list
for i in my_list:
 print(i)

Then you will get this
output:
Studentname1 at Time on Day,
Studentname2 at Time on Day

If you want Json Response then simply convert it into a Dictionary list

data = []
    for i in my_list:
        data.append(i)
return JsonResponse(data, safe=False)

CodePudding user response:

You can just loop through queryset and call str() on each object

for obj in tn_mon:
   print(str(obj))

OR store the obj in list

tn_mon_list = []
for obj in tn_mon:
   tn_mon_list.append(str(obj))
   
  • Related