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 PostModel
s (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, soPost
instead ofPostModel
, andKeyConcept
instead ofKeyConceptModel
.
Β
Note: since you iterate over
object_list
(in the outer loop) the item is a single post, so I advice to name itpost
, instead ofposts
, 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 aname
attribute, and you want the function to be able to process both. Therefore I advise to remove thepost_
prefix of the attributes.