I have a very basic ‘news feed’ page that uses generic relations, with the following model:
class RecentActivity(models.Model):
event_type = models.IntegerField(choices=EVENT_TYPES)
timestamp = models.DateTimeField()
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
credits = models.ManyToManyField('videos.VideoCredit', blank=True)
I am using signals to listen for when an object is created and checking to make sure it exists (i.e., it was not deleted) in the view before showing it. It is a very basic page, with only a couple dozen lines of code to generate it. However, it is generating tons of db queries! On a page of about 20 recent activity objects, it takes about 120 queries, and I estimate it’ll max out around 200 queries.
What would be the best way to get around this? My primary concern is not in reducing the number of queries, but in making the page load as fast as possible. (My first thought was denormalizing.)
Note that the page is not dynamic per-user, but will be the same for all users. Thank you.
Hard to say without more information but the usual steps I take are:
Looking at your model, you are probably accessing content_type and then content object. If you follow credits at all you’ll easily hit that number of queries.