I worked previously with select_relatedand prefetch_related, and it worked great.
I am working on the current project, and for some reason I can’t understand why my prefetch query is not working correctly, so I get a lot of redundant database calls.
My models:
class User(models.Model):
user_extra_info = models.ManyToManyField(
AppGeneralData,
through='UserExtraInfo',
null=True,
blank=True
)
class AppGeneralData(models.Model):
title = models.CharField(max_length=255)
type = models.PositiveSmallIntegerField(
choices=GENERAL_DATA_TYPE
)
class UserExtraInfo(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
info_item = models.ForeignKey(AppGeneralData)
QuerySet:
User.objects.all().prefetch_related(
Prefetch(
'userextrainfo_set',
queryset=UserExtraInfo.objects.select_related('info_item').all()
)
)
Problem :
When you repeat the request and call the subquery, it does not extract it from the cached set of requests:
for user in qs:
user.userextrainfo_set.filter(
info_item__type=general_data_type
).values_list(
'info_item__title', flat=True
))
The subquery just goes to the database on every call, and I don’t understand what is missing.
Thanks.
source
share