Does select_related work for GenericRelation relations, or is there a reasonable alternative? At the moment Django's doing individual sql calls for each item in my queryset, and I'd like to avoid that using something like select_related.
class Claim(models.Model):
proof = generic.GenericRelation(Proof)
class Proof(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
I'm selecting a bunch of Claims, and I'd like the related Proofs to be pulled in instead of queried individually.
Looks like select_related and GRs don't work together. I guess you could write some kind of accessor for Claim that gets them all via the same query. This post gives you some pointers on raw SQL to get generic objects, if you need them
There isn't a built-in way to do this. But I've posted a technique for simulating
select_related
on generic relations on my blog.Blog content summarized:
We can use Django's
_content_object_cache
field to essentially create our ownselect_related
for generic relations.you can use .extra() function to manually extract fields :
The .filter() will do the join, the .extra() will pull a field. proof_proof is the SQL table name for Proof model. If you need more than one field, specify each of them in the dictionnary.