Evgenii Legotckoi
Aug. 26, 2019, 1:51 p.m.

Django - Tutorial 047. How to do select_related and prefetch_related for an authenticated user

Imagine that for an authenticated user, when opening pages, some requests are constantly being executed, for example, an additional list of notifications is loaded, as well as his profile. And we use this information in templates, for example this way.

{% if user.is_authenticated %}
    {{ user.profile.avatar }}
    {{ user.notices.count }}
{% endif %}

Both profile and notices are data models for which a query to the database is required, and each query is an additional connection and additional data retrieval, which increases the response time of the site. At the same time, Django uses the mechanism of sampling the corresponding models in a single database query to speed up the selections.

It turns out that the three initial queries can be combined into one query. But if everything is more or less clear with ordinary models, then a problem arises with the authenticated user’s object, since at first glance it is not clear when and where user data is taken.

Answer: An authenticated user gets into the authentication backend.

Therefore, we need to write our own authentication backend so that we can execute select and prefetch requests when searching for a user.

It will look as follows.

# -*- coding: utf-8 -*-

from django.contrib.auth import get_user_model


class MyBackend:

    def get_user(self, user_id):
        try:
            return get_user_model().objects.select_related('profile').prefetch_related('notices').get(pk=user_id)
        except get_user_model().DoesNotExist:
            return None

And for this to work, you need to add our authentication backend in the settings.

AUTHENTICATION_BACKENDS = (
    'my_app.backends.MyBackend',
    'django.contrib.auth.backends.ModelBackend',
)

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    April 16, 2025, 5:08 p.m.
    Благодарю за отзыв. И вам желаю всяческих успехов!
  • IscanderChe
    April 12, 2025, 5:12 p.m.
    Добрый день. Спасибо Вам за этот проект и отдельно за ответы на форуме, которые мне очень помогли в некоммерческих пет-проектах. Профессиональным программистом я так и не стал, но узнал мно…
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…