New to Django, third question on it today…
I have the following (simplified) models defined:
class Band(models.Model):
bandname = models.CharField('Band name', max_length=300)
class Release(models.Model):
title = models.CharField(max_length=300)
artist = models.ManyToManyField('Band')
formats = models.ManyToManyField('Format')
class Format(models.Model):
kind = models.CharField(max_length=300)
class Song(models.Model):
title = models.CharField(max_length=500)
release = models.ForeignKey('Release')
(I’ve removed extra fields for the sake of readability)
Now, when I try to run the following query, it adds hundreds of extra queries to the page:
s = Song.objects.all() # adds 367 queries
I’ve tried changing it to this:
s = Song.objects.select_related('band', 'release').all() # adds 245 queries
This still sucks and I don’t know what else I can do. There are 122 songs in my database, on 52 releases, by 39 bands. Not sure if this helps but I’m at a loss.
Any tips on how to optimise this? I need to be able to show the band and release name for each Song. A Release is ManyToMany for Band because some of them are split releases by multiple artists.
thanks,
Matt
Django
select_relateddoes not follow many-to-many relationships, and I’m guessing that is what is causing the large query count.My suggestion is to use
values(), anddouble__underscore__notationto get the required values. Something similar to this should work on django 1.3 and above: