Home > Blockchain >  How to get rid of <QuerySet[]> tag when getting the data on my template from the database? Dja
How to get rid of <QuerySet[]> tag when getting the data on my template from the database? Dja

Time:12-17

I'm having a bad time figuring this out through searching different stackoverflow question but I'm using a function based view to make my day simplier. But when i'm retrieving this single data from a database and showing only one record using slice. It throws beside it a tag which commonly see when we test print in our terminals. But how exactly to get rid of this?

tutorials = Tutorial.objects.values_list('id', flat=True)
courses = Course.objects.all()
tutorial_title = Tutorial.objects.filter(id__in=tutorials).values('title').values_list('title', flat=True)
context = {'tutorial': tutorials,'courses': courses, 'tutorial_title': tutorial_title}

Here's my code snippet, where when i call {{ tutorial_title | slice:'1'}}. It should only call one latest record, which works flawlessly but there is a <QuerySet tag beside the shown data.

CodePudding user response:

Why not just pass it to the template as a signle title:

courses = Course.objects.all()
tutorial_titles = ', '.join(Tutorial.objects.values_list('title', flat=True))
context = {
    'courses': courses,
    'tutorial_titles': tutorial_titles
}

Here tutorial_titles is a comma seperated string of tutorial titles.

Or if you only want the first title:

courses = Course.objects.all()
tutorial_title = Tutorial.objects.values_list('title', flat=True).first()
context = {
    'courses': courses,
    'tutorial_title': tutorial_title
}

CodePudding user response:

I think i just discover the answer by an accident. So i know the QuerySet is a List so in my views.py, I think i could just set a for loop on the Query itself and throw it to a empty List that will throw to the template using the context. lmao

tutorials = Tutorial.objects.values('id')
courses = Course.objects.all()
**tutorial_titleList = []**
tutorial_title = Tutorial.objects.filter(id__in=tutorials).values('title').values_list('title', flat=True)
**for tutorial in tutorial_title:
    tutorial_titleList.append(tutorial)**
context = {'tutorial': tutorials,'courses': courses, 'tutorial_title': tutorial_titleList}

and in my template tag. Since it still returns a List, i just put | join: "" template tag beside and and bwalaahh

  • Related