R
R
Rrooom2014-10-22 11:32:47
Django
Rrooom, 2014-10-22 11:32:47

How to get rid of extra requests in Django?

In Django, I use a raw query, which is pretty straight forward:
object_list = MyModel.objects.raw(...)
There are two problems with this.
The first - even in the view, the aggregated data in the loop is considered:

for each in object_list:
    total[...] += each.x
    total[...] += each.x

Well, then, once again, according to the data, they are run in a loop already in the template. And for some reason, django does not cache the result - but the request is executed again.
Second problem. In the template, when rendering results, django will automatically refer to the other model associated with the ForeignKey. Moreover, for each object it executes a request - hundreds of requests, stupidly in order to take the category name!
How to deal with it?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis Egorov, 2014-10-22
@ur001

I've been able to avoid using .raw() on almost every big project , so I asked you what's inside. There are almost certainly workarounds.
In order to be sure that the query will not be executed multiple times, it can be immediately turned into a list:
Prefetch_related_objects is usually used to perform prefetch_related in raw queries , although this function is not documented in Django:

from django.db.models.query import prefetch_related_objects
object_list = list(MyModel.objects.raw(...))
prefetch_related_objects(raw_qs, ['fk_field', 'another_fk_field', ...])

To learn when and what queries are executed, it is convenient to use the debugsqlshell console from the django debug toolbar (which you most likely use).

V
Vladimir Sokolovsky, 2014-10-22
@inlanger

Either screw caching yourself, or put up with it. For Django, this is fine.

A
alternativshik, 2014-10-22
@alternativshik

Regarding the latter - prefetch_related will help you.
Regarding the first - in the same cycle, just make another sheet with data from the object_list data and djanga will not make a request 2 times.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question