How to restrict prefetch_related in Django?

Let's say I have image objects with many relationships with tags.

now, I am creating a search view for displaying images, and tags are displayed for each image, it is obvious that the smart thing is to pre-select tags for images.

however, I only show 15 images each time, but I need to evaluate the entire set of queries in order to display how many results in total are. so I need to pre-select tags only for the first 15 elements

If I pre-subtract the tags before slicing:

images = watson.filter(queryset, query).prefetch_related('tags')
amount = images.count()
images = images[:15]

this is very bad because there can be thousands of results, and each result can have many tags.

but if I cut first:

images = watson.filter(queryset, query).prefetch_related('tags')[:15]
amount = images.count()

prefetch 15 , , , .

:

images = watson.filter(queryset, query)
amount = len(images)
images = images.prefetch_related('tags')[:15]

, prefetch db.

, , 15.

+4
1

count(), prefetch_related() .

images = watson.filter(queryset, query)
amount = images.count()
images = images.prefetch_related('tags')[:15]

, 15 , . count() , len(), , .

+1

Source: https://habr.com/ru/post/1610434/


All Articles