Sunday, March 30, 2014

Re: Allow the Prefetch queryset to be used with GenericForeignKey

That would be awesome, somebody has a solution for this?

On Sunday, February 16, 2014 2:53:55 PM UTC-3, Robert Kajic wrote:
I would love it if the Prefetch object allowed me to pass in custom querysets when prefetching related generic foreign fields. Specifically I want this in order to call select_related on each subgroup.
For now I've subclassed the GenericForiengKey class, overriding get_prefetch_queryset, to allow me to use modelless querysets like this:

        Prefetch('obj', queryset=QuerySet().select_related(
            "user", "poem__user", "consumer", "producer"

In get_prefetch_queryset, for each subgroup, I copy the select_related options from the modelless queryset to the subgroup queryset:

qs = ct.get_all_objects_for_this_type(pk__in=fkeys)
# Copy any select related options from queryset to qs
qs = self.combine_select_related(qs, queryset)

Initially I thought I would simply be able to combine the two querysets using QuerySet.__or__, but I noticed that Query.combine refuses to run unless both queries are on the same model. Would there be any harm in allowing it to combine Queries even if the qeries are not on the same model, as long as one of the queries doesn't have a model at all? Then the above could be changed into:

# Copy any select related options from queryset to qs
qs |= queryset

This would have the added benefit of copying other options other than select_related.

I know this is problematic because you may not want to combine the same queryset with each individual group. Ideally, the developer would be able to specify a different queryset for each group kind.

        Prefetch('obj', queryset=QuerySet().select_related(
            "user", "poem__user", "consumer", "producer"

Does anyone have any thoughts on this? 

You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to
To post to this group, send email to
Visit this group at
To view this discussion on the web visit
For more options, visit

No comments:

Post a Comment