Reduce number of queries required to render an entries list, especially the home page

This commit is contained in:
Danielle McLean 2018-01-24 13:18:22 +11:00
parent 957fc4ada7
commit 75e08aa1b2
Signed by untrusted user: 00dani
GPG key ID: 5A5D2D1AFF12EEC5
4 changed files with 42 additions and 12 deletions

View file

@ -42,7 +42,7 @@ class Cat(models.Model):
class EntryManager(models.Manager):
def get_queryset(self):
qs = super(EntryManager, self).get_queryset()
return qs.select_related('author').prefetch_related('syndications')
return qs.select_related('author').prefetch_related('cats', 'syndications')
class Entry(ModelMeta, TimeStampedModel):

View file

@ -16,11 +16,14 @@ def index(request, page):
def url(page):
kwargs = {'page': page} if page != 1 else {}
return reverse('home:index', kwargs=kwargs)
query = User.objects.prefetch_related('entries', 'profiles', 'keys')
user = get_object_or_404(query, pk=1)
entries = user.entries.filter(kind__in=kinds.on_home)
user = request.user
if not user:
user = get_object_or_404(User, pk=1)
entries = user.entries.filter(kind__in=kinds.on_home)
entries = pagination.paginate(queryset=entries, reverse=url, page=page)
# If we got a valid HTTP response, just return it without rendering.
if hasattr(entries, 'content'):
return entries

View file

@ -0,0 +1,20 @@
# -*- coding: utf-8 -*-
# Generated by Django 1.11.9 on 2018-01-24 02:11
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0010_auto_20171206_2211'),
]
operations = [
migrations.AlterModelManagers(
name='user',
managers=[
],
),
]

View file

@ -31,7 +31,14 @@ class Site(models.Model):
ordering = ('name',)
class UserManager(models.Manager):
def get_queryset(self):
return super(UserManager, self).get_queryset().prefetch_related('keys', 'profiles')
class User(ModelMeta, AbstractUser):
objects = UserManager()
avatar = models.ImageField(upload_to=avatar_path)
note = models.TextField(blank=True)
xmpp = models.EmailField(blank=True)
@ -61,17 +68,17 @@ class User(ModelMeta, AbstractUser):
@cached_property
def facebook_id(self):
try:
return self.profiles.filter(site__name='Facebook').values('username')[0]['username']
except IndexError:
return None
for p in self.profiles.all():
if p.site.name == 'Facebook':
return p.username
return None
@cached_property
def twitter_username(self):
try:
return '@' + self.profiles.filter(site__name='Twitter').values('username')[0]['username']
except IndexError:
return None
for p in self.profiles.all():
if p.site.name == 'Twitter':
return '@' + p.username
return None
@property
def json_ld(self):