[Django]-Object_list does not show correct data in template

3πŸ‘

βœ…

In your template you write:

<!-- this will iterate again over the same list -->
{% for keyword in object_list.all %}
    <p>{{ keyword }}</p>
{% endfor %}

But here object_list is your QuerySet of the articles. The fact that you call .all() only means that the for loop will thus again iterate over all PostModels (well the .all() is used to make it explicit that you do no filtering).

If you want to iterate over the post_keyconcept, you need to call posts.post_keyconcept.all instead:

{% for keyword in posts.post_keyconcept.all %}
    <p>{{ keyword }}</p>
{% endfor %}

Since you want to render the key_concepts of all posts, you better use .prefetch_related(..) in the ListView such that the keywords are fetched in a constant number of queries, so:

class ListPostGDV(ListView):
    model = PostModel
    queryset = PostModel.objects.prefetch_related('post_keyconcept')

    # ...

Note: normally the names of models are singular and without the Model suffix, so Post instead of PostModel, and KeyConcept instead of KeyConceptModel.

Β 

Note: since you iterate over object_list (in the outer loop) the item is a single post, so I advice to name it post, instead of posts, since this otherwise only introduces confusion.

Β 

Note: you prefix all attributes with post_ which is a bit redundant. It also prevents making use of duck typing when for example two models have a name attribute, and you want the function to be able to process both. Therefore I advise to remove the post_ prefix of the attributes.

Leave a comment