Search code examples
djangodjango-templatesdjango-querysetdjango-template-filters

Get the value in queryset in Django template


I have used Django to develop a web app. In the View function, I have rendered a queryset list to frontend. In my case, title table is book information, and Material is the detailed info of this book is attached to which course and if this attached relation is "discard". is_discard is in Material table, and not the book discard or not. In Material table several books attached to a course, and discard status is not by book but by book-course pair, as some books may discard in one course but active in other courses

view.py:

def render_2(request):
    books = Title.objects.filter(name=title).values()
    query_results_book_is_discard = 
    Material.objects.filter(id=book_id).values('is_discard')
    return render(request, 'main.html',
                              context= 
    {'query_results_book_is_discard':query_results_book_is_discard, 
      'book', books})

In the frontend, the query_results_book_is_discard variable shows the following format :

<QuerySet [{'is_discard': True}, {'is_discard': False}, {'is_discard': False}, {'is_discard': False}, {'is_discard': True}, {'is_discard': True}, {'is_discard': False}]> 

The query_results_book_is_discard variable is in a loop in frontend Django template, I want to use the forloop counter to get the value(True or False) to use if condition to check. I haved tried in main.html:

  {% for book in books %}
     {% if query_results_book_is_discard.counter0 != False %}
 ...

and

{% if query_results_book_is_discard.counter0.is_discard != False %}

and

 {% if query_results_book_is_discard.is_discard.counter0 != False %}

All failed.

How could I get the True or False value in query_results_book_is_discard to use if condition?


Solution

  • I would recommend you to create a custom template tag that allows you to access a specific index of a list in the template, as follows.

    Your app file tree structure should have something like this:

    your_app/
        __init__.py
        models.py
        templatetags/
            __init__.py
            your_app_extras.py
        views.py
    

    Then, in your custom template tag file.

    your_app_extras.py

    from django import template
    register = template.Library()
    
    @register.filter
    def index(indexable, i):
        return indexable[i]
    

    Then, in your template, load your custom template tags:

    {% load your_app_extras %}
    

    Then, in your for-loop, you use the following:

    {% for book in books %}
        {% with query_results_book=query_results_book_is_discard|index:forloop.counter0 %}
            {% if query_results_book.is_discard %}
        {% endwith %}
    {% endfor %}