Opened 2 months ago

Last modified 2 months ago

#36606 closed Cleanup/optimization

Optimize QuerySet.values_list(flat=True) with no fields — at Initial Version

Reported by: Adam Johnson Owned by:
Component: Database layer (models, ORM) Version: dev
Severity: Normal Keywords:
Cc: Triage Stage: Accepted
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Currently, QuerySet.values_list() ensures that no more than 1 field is set (source):

        if flat and len(fields) > 1:
            raise TypeError(
                "'flat' is not valid when values_list is called with more than one "
                "field."
            )

However, it also allows the case where *no* fields are declared, for which all fields are fetched, only to throw away all but the first one (source):

class FlatValuesListIterable(BaseIterable):
    """
    Iterable returned by QuerySet.values_list(flat=True) that yields single
    values.
    """

    def __iter__(self):
        queryset = self.queryset
        compiler = queryset.query.get_compiler(queryset.db)
        for row in compiler.results_iter(
            chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size
        ):
            yield row[0]

I think we can optimize this case to select only the first field in the model instead, maintaining semantics while avoiding overfetching.

Change History (0)

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