views:

139

answers:

2

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.

+1  A: 

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

stevejalim
+2  A: 

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.

Daniel Roseman