How to use select_related with GenericForeignKey in django?

I have a situation where a large number of objects of a certain class are repeated, and they take a huge amount of time to process, because I can not pre-select data using select_related .

The class in question looks something like this:

 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 tried using select_related as below, but obviously not working

 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?

+6
source share
1 answer

This is not select_related what you are looking for. This is prefetch_related , which

Supports GenericRelation and GenericForeignKey prefetching.

Therefore, your basic command will be:

Offer.objects.all().prefetch_related('content_object')

+10
source

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


All Articles