S
S
Sama Samsonov2017-02-16 11:58:04
Django
Sama Samsonov, 2017-02-16 11:58:04

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})

How to put a for loop in a variable or return a value in a template?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
iMrDron, 2017-02-16
@samuser

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))
)

In a cycle, making queries to the database is unacceptable at all! Study the annotations, if it happens that their capabilities are not enough, let's say you need to do more intermediate calculations, then you need to go the other way to get all the artists from the database, get all the albums for artists filtered by genres with one request, and already iterate by the results and count what you need .

E
Egor Kazantsev, 2017-02-16
@saintbyte

Make a method for the model and think about caching.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question