I have a situation wherein a large number of objects of a particular class are being iterated over, and they take a huge amount of time for processing because I can't pre-select data using select_related
.
The class in question goes something like below
from django.contrib.contenttypes.models import ContentType
from django.db import models
class Offer(models.Model):
...
object_id = models.PositiveIntegerField(db_index = True)
content_type = models.ForeignKey(ContentType, db_index = True)
content_object = generic.GenericForeignKey('content_type', 'object_id')
...
I have tried using select_related like below, but it obviously doesn't work
offerList = Offer.objects.select_related('content_type', "content_object"
).filter(content_type=ContentType.objects.get_for_model(SomeObject),
object_id=someobject.id)
So, how can I use select_related
with GenericForeignKey in django?
In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects. In this article, we will see how it reduces the number of queries and make the program much faster.
In Django, select_related and prefetch_related are designed to stop the deluge of database queries that are caused by accessing related objects. I basically tried to figure out how and how many queries it reduces and, in this article, I will describe my findings. You can find the source code on GitHub.
It is not select_related
what you are looking for. It is prefetch_related, which
supports prefetching of GenericRelation and GenericForeignKey.
Therefore, your base command would be:
Offer.objects.all().prefetch_related('content_object')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With