[Fixed]-Django one-to-many queries

1๐Ÿ‘

By default the related objects (through a ForeignKey on the other model) are accessible trough <modelname>_set zo in this case that is band.album_set (note this is a Manager attribute so you will probably use band.album_set.all() most of the time).

I personally prefer to give al my ForeignKey fields a related_name so I can name the attribute on the other model. The next example gives the Band the attribute band.albums.

class Band(models.Model):
    # Band definition

class Album(models.Model):
    band = models.ForeignKey(Band, related_name='albums')
    # Rest of album definition
๐Ÿ‘คjgadelange

0๐Ÿ‘

Could be great if you share your models definition. But I hope this helps you:

If you want to retrieve the Albums for a specific band:

band = Band.objects.get(...)
band_albums = Album.objects.filter(band=band)

That will return the albums for a band.

If you want retrive albums for all the bands:

bandList = Band.objects.all().select_related('album_set')

This will return the bans as before, but will cache the albums.

๐Ÿ‘คGocht

Leave a comment