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.

  1. {% if user.is_authenticated %}
  2. {{ user.profile.avatar }}
  3. {{ user.notices.count }}
  4. {% 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.

  1. # -*- coding: utf-8 -*-
  2.  
  3. from django.contrib.auth import get_user_model
  4.  
  5.  
  6. class MyBackend:
  7.  
  8. def get_user(self, user_id):
  9. try:
  10. return get_user_model().objects.select_related('profile').prefetch_related('notices').get(pk=user_id)
  11. except get_user_model().DoesNotExist:
  12. return None
  13.  

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

  1. AUTHENTICATION_BACKENDS = (
  2. 'my_app.backends.MyBackend',
  3. 'django.contrib.auth.backends.ModelBackend',
  4. )

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html