Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use select_related with GenericForeignKey in django?

Tags:

python

django

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?

like image 497
Anshul Goyal Avatar asked Dec 04 '14 10:12

Anshul Goyal


People also ask

What does Select_related do 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.

What is Select_related and Prefetch_related 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. 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.


1 Answers

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')

like image 77
raratiru Avatar answered Oct 09 '22 11:10

raratiru