From 7d485d5d75bd9faab0b949fd34d4f098f8079452 Mon Sep 17 00:00:00 2001 From: Iacopo Spalletti Date: Sat, 2 Apr 2016 12:39:39 +0200 Subject: [PATCH] Fixed #22268 -- Documented values_list() behavior for multivalued relations.a Thanks Sai Krishna for the initial patch. --- docs/ref/models/querysets.txt | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/docs/ref/models/querysets.txt b/docs/ref/models/querysets.txt index d60b3a5866..ef0bd221e1 100644 --- a/docs/ref/models/querysets.txt +++ b/docs/ref/models/querysets.txt @@ -637,6 +637,30 @@ achieve that, use ``values_list()`` followed by a ``get()`` call:: >>> Entry.objects.values_list('headline', flat=True).get(pk=1) 'First entry' +``values()`` and ``values_list()`` are both intended as optimizations for a +specific use case: retrieving a subset of data without the overhead of creating +a model instance. This metaphor falls apart when dealing with many-to-many and +other multivalued relations (such as the one-to-many relation of a reverse +foreign key) because the the "one row, one object" assumption doesn't hold. + +For example, notice the behavior when querying across a +:class:`~django.db.models.ManyToManyField`:: + + >>> Author.objects.values_list('name', 'entry__headline') + [('Noam Chomsky', 'Impressions of Gaza'), + ('George Orwell', 'Why Socialists Do Not Believe in Fun'), + ('George Orwell', 'In Defence of English Cooking'), + ('Don Quixote', None)] + +Authors with multiple entries appear multiple times and authors without any +entries have ``None`` for the entry headline. + +Similarly, when querying a reverse foreign key, ``None`` appears for entries +not having any author:: + + >>> Entry.objects.values_list('authors') + [('Noam Chomsky',), ('George Orwell',), (None,)] + ``dates()`` ~~~~~~~~~~~