Django - selecting the related objects from the reverse model - e.g reverse select_related

StackOverflow https://stackoverflow.com/questions/22518972

  •  17-06-2023
  •  | 
  •  

سؤال

I have the following models (just for example sake):

class Song(models.Model):
    name = CharField()
    album = ForeignKey(Album, related_name='songs')

class Album(models.Model):
    name = CharField()
    genre = ForeignKey(Genre, related_name ='albums')

class Genre(models.Model):
    name = CharField()

I'm looking for a way to fetch all songs related to albums that relate to a specific (filtered) genres or genre, while doing the joins in the DB and not "in memory".

I know I can use the select_related clause to go the otherway around (following the good example for this blog post:

songs = Song.objects.select_related("album").select_related('genre').all()

and the the queryset would already include all the genre properties on the song album without hitting the DB again.

My question is how to this the other way around: start from a specific (or filtered) genre and get all songs -d own the foreign key chain.

هل كانت مفيدة؟

المحلول

Would

Song.objects.select_related("album").filter(album__genre=GENRE_YOU_WANT)

be what you want? For normal foreign keys, should should use just one query.

نصائح أخرى

You can get all songs related to a genre by using a filter:

genre = Genre.objects.get(name='pop')
songs_in_genre = Songs.objects.filter(album__genre=genre)

If you want to fetch albums, and all their related songs at once, then use prefetch_related:

albums = Album.objects.filter(genre="rock").prefetch_related('songs')
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top