Opened 11 years ago

Closed 11 years ago

Last modified 6 months ago

#20923 closed New feature (wontfix)

Unable to use fields from prefetch_related() in only() and defer()

Reported by: alexpirine Owned by: nobody
Component: Database layer (models, ORM) Version: 1.5
Severity: Normal Keywords: defer only ForeignKey reverse relationship
Cc: as@… Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

If I run the following query, I get the same error as seen in #14694:

ParentModel.objects.prefetch_related('child_model').only('parent_attribute', 'childs__child_atrtibute').all()

I guess it is not really a bug, as using only() and defer() in combination with prefetch_related() is not documented (documentation only mentions the use of select_related() with defer()).

But it could be a useful feature: is there a reason to support select_related() but not prefetch_related()?

I hope that an improvement of the patch for #14694 can enable this feature.

P.S. I wasn't able to fix it by myself, due to my lack of understanding of how django.db.models.sql.query.deferred_to_data() works. Simply removing and field.field.unique in django.db.models.sql.query.is_reverse_o2o() makes the error message disappear, but the instructions in only() remain ignored.

Change History (6)

comment:1 by as@…, 11 years ago

comment:2 by alexpirine, 11 years ago

Cc: as@… added

I registered to follow this ticket.

comment:3 by Anssi Kääriäinen, 11 years ago

I think a better way is to add custom query support to prefetch_related (or, #17001). Main reason is that I believe implementation of communicating the only/defer data from the main query to the prefetch queries will be hard to do cleanly.

comment:4 by Anssi Kääriäinen, 11 years ago

Resolution: wontfix
Status: newclosed

Forgot to wontfix this...

in reply to:  3 comment:5 by alexpirine, 11 years ago

Replying to akaariai:

I think a better way is to add custom query support to prefetch_related (or, #17001). Main reason is that I believe implementation of communicating the only/defer data from the main query to the prefetch queries will be hard to do cleanly.

Thanks, it looks interesting. If I understood it correctly, I could pass the only() attribute to the custom queryset:

ParentModel.objects.prefetch_related(
  R('child_model', to_attr = 'childs', qs = ChildModel.objects.only('child_attribute')
).only('parent_attribute').all()

which would answer this issue.

comment:6 by Natalia Bidart, 6 months ago

#35442 may be a duplicate of this one.

Note: See TracTickets for help on using tickets.
Back to Top