[Fixed]-Efficient way to filter a hierarchical structure in Django?

1👍

I ended up with the following:

filters = { "genre": 'funkadelic mariachi' }
artist = None
album = None
result = []

# select_related() fetches our chosen songs, and their albums and artists, in a single query
for song in Song.objects.select_related(
        'album__artist').filter(**filters):

    if album != song.album and album != None:
        result.append('End of Album')

    if artist != song.album.artist:
        if artist != None:
            result.append('End of Artist')
        artist = song.album.artist
        result.append(artist)

    if album != song.album:
        album = song.album
        result.append(album)

    result.append(song)

if result:
    result.append('End of Album')
    result.append('End of Artist')

Not so pretty, but much more efficient. Perhaps prefetch_related() would allow to keep the three loops, using Prefetch(‘artist’, to_attr=’filtered_artists’) or so, but with one extra query per turtle.

👤Chema

Leave a comment