Answer the question
In order to leave comments, you need to log in
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
Answer the question
In order to leave comments, you need to log in
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', ...])
Either screw caching yourself, or put up with it. For Django, this is fine.
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 questionAsk a Question
731 491 924 answers to any question