Answer the question
In order to leave comments, you need to log in
How to write a loop inside views.py in Django?
How to write a loop inside views.py in Django ?
def query1(request):
genres = Genre.objects.filter(name__in=["Traditional music", "Juz"])
ids = [g.id for g in genres]
artists = Artist.objects.all()
# ????
for artist in artists:
artist.album_count = artist.album_set.filter(genres__in=ids).count()
# ^^^
artists.order_by("-album_count")
return render(request, 'joiners/joiners_1.html', {"genres":genres, "artists":artists, "ids":ids})
Answer the question
In order to leave comments, you need to log in
All this can be done with annotations like this:
artists = (
Artist.objects
.filter(album_set__genres__name__in=["Traditional music", "Juz"])
.annotate(album_count=Count('album_set', distinct=True))
)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question