#20927: Include known related fields for subclassed "QuerySet.only"
-------------------------------------+-------------------------------------
Reporter: lvo@… | Owner: nobody
Type: Bug | Status: new
Component: Database layer | Version: 1.5
(models, ORM) | Keywords: queryset, only, related
Severity: Normal | manager, manager
Triage Stage: Unreviewed | Has patch: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
I have a model like these:
{{{
#!python
class PNRSegment(models.Model):
pnr = models.ForeignKey('booking.PassengerNameRecord',
related_name="segments")
arrival_datetime = models.DateTimeField()
objects = PNRSegmentManager()
}}}
Also i wrote my own Manager with own QuerySet:
{{{
#!python
class PNRSegmentManager(models.Manager):
use_for_related_fields = True
def get_query_set(self):
return PNRSegmentQuerySet(self.model, using=self._db)
def latest_datetime(self):
return self.get_query_set().latest_datetime()
class PNRSegmentQuerySet(QuerySet):
def latest_datetime(self):
try:
return self.order_by('-arrival_datetime')[0].arrival_datetime
except IndexError:
return None
}}}
I noticed that `QuerySet.only` has strange behavior:
{{{
#!python
# When launching pdb into PNRSegmentQuerySet.latest_datetime:
(Pdb) pp self
[<PNRSegment: PNRSegment object>, <PNRSegment: PNRSegment object>]
(Pdb) pp self.count()
2
(Pdb) pp self[0]
<PNRSegment: PNRSegment object>
(Pdb) pp self.only('arrival_datetime').count()
2
(Pdb) pp self.only('arrival_datetime')[0]
*** IndexError: IndexError(("PNRSegment matching query does not exist.
Lookup parameters were {'pk': None}",),)
}}}
After tracing of `QuerySet.clone` i found my error: when subclassing
QuerySet for related manager, each `QuerySet.only` call should contain
related field:
{{{
#!python
(Pdb) pp self.only('arrival_datetime', 'pnr')[0]
<PNRSegment_Deferred_airline_code_class_code_ ... cutted ...>
}}}
I think that this is not obvious behaviour. `QuerySet.only` should
authomatically include all fields from `QuerySet._known_related_objects`.
--
Ticket URL: <https://code.djangoproject.com/ticket/20927>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/062.20fe16c86ee05dfad87f7aa2d850f0b9%40djangoproject.com.
For more options, visit https://groups.google.com/groups/opt_out.