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_related(
        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)
ret_val.extend(qs)

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_related(
        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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/7a7a4157-51b2-4e89-8cb0-ce25b5445b36%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment