Evgenij LegotskojAug. 26, 2019, 3:51 a.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 %}

ADS

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',
)
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.
- company blog
Support the author Donate

Comments

Only authorized users can post comments.
Please, Log in or Sign up
Fornex

Let me recommend you a great European Fornex hosting.

Fornex has proven itself to be a stable host over the years.

For Django projects I recommend VPS hosting

Following the link you will receive a 5% discount on shared hosting services, dedicated servers, VPS and VPN

View Hosting
MP

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
SI

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
k

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:90points,
  • Rating points8
Last comments
H

Python: How to Test Internet Speed

There may be no animus franchise that opens with as dull-witted and satiating a ritual as Scream. As the shaping followers’s logo appears on wall, we rather enter upon hearing the ringing of a l…
A
  • Andrew
  • Jan. 12, 2022, 11:41 a.m.

Qt/C++ - Lesson 038. Switching between windows in the Qt

Здравствуйте, а как сделать чтобы второе и третье окно не сохраняли свои параметры а создавались заного? Только начинаю изучать прогграмирование и пишу протенькую игру сделал 2 окна, одно с меню…
j
  • juvf
  • Dec. 28, 2021, 11:56 p.m.

Deploying Qt and QML Applications on Linux and Windows

написал приложение, холоворд на qt виджетах, без qml. Из визарда QtCreator. Собрал кросскомпилятором. Нужно перенести на таргет. juvf@juvf-VirtualBox:~/qtWs/test/imx6/release$ ~/CQtDeploye…
AO

Qt/C++ - Lesson 023. Moving QGraphicsItem on QGraphicsScene with mouse help

А есть возможность передавать координаты классу, что-бы он рисвал, допустим линию?
q

Django - Tutorial 036. How to add authentication through social networks. VKontakte

Добавь в setting.py строку: SOCIAL_AUTH_VK_OAUTH2_API_VERSION = '5.81'
Now discuss on the forum
AB

Sorting the added QML elements in the ListModel

I am writing an alarm clock in QML, I am required to sort the alarms in ascending order (depending on the date or time (if there are several alarms on the same day). I've done the sorting …
VK

Как получить ссылку на обьект присылающий сигнал через сигнал/слот?

Вот и ответ: Спасибо Александру за подсказку. void Core::onLogin(QString m_login) { Worker *m_worker = qobject_cast (sender()); hashLogin.insert(m_login, m_wor…
v

подтвердить значение в SpinBox

Мне необходимо подтвердить значение в SpinBox нажатием клавиши Enter и перевести фокус на другое поле. self.doubleSpinBox.returnPressed.co nnect(self.pressedKeys) def pressedKeys(sel…

Сортировка по дате и времени QSortFilterProxyModel QSqlRelationalTableModel

Добрый день. Наследуйте модель сортировки от QSortFilterProxyModel и переопределите метод QSortFilterProxyModel::lessThan таким образом, чтобы вы забирали через индексы дату и в…

Как создать класс вызывающий функции по входному числу 0-255?

Вы в любом случае упрётесь в маршрутизацию сообщения от этих цифр 0-255 до вызова конкретных методов и функций. А все эти пляски метасистемой Qt в данном случае лишь усложнение кода. Если …
About
Services
© EVILEG 2015-2021
Recommend hosting TIMEWEB