@@ -395,20 +395,10 @@ def build_query(self, columns=None):
395395 return query
396396
397397 def get_columns (self ):
398- """
399- Return a tuple of (name, expression) with the columns and annotations
400- which should be loaded by the query.
401- """
402398 select_mask = self .query .get_select_mask ()
403399 columns = (
404400 self .get_default_columns (select_mask ) if self .query .default_cols else self .query .select
405401 )
406- # Populate QuerySet.select_related() data.
407- related_columns = []
408- if self .query .select_related :
409- self .get_related_selections (related_columns , select_mask )
410- if related_columns :
411- related_columns , _ = zip (* related_columns , strict = True )
412402
413403 annotation_idx = 1
414404
@@ -427,11 +417,30 @@ def project_field(column):
427417 annotation_idx += 1
428418 return target , column
429419
430- return (
431- tuple (map (project_field , columns ))
432- + tuple (self .annotations .items ())
433- + tuple (map (project_field , related_columns ))
434- )
420+ selected = []
421+ if self .query .selected is None :
422+ selected = [
423+ * (project_field (col ) for col in columns ),
424+ * self .annotations .items (),
425+ ]
426+ else :
427+ for _ , expression in self .query .selected .items ():
428+ # Reference to an annotation.
429+ if isinstance (expression , str ):
430+ expression = self .annotations [expression ]
431+ # Reference to a column.
432+ elif isinstance (expression , int ):
433+ expression = columns [expression ]
434+ selected .append (project_field (expression ))
435+
436+ # Populate QuerySet.select_related() data.
437+ related_columns = []
438+ if self .query .select_related :
439+ self .get_related_selections (related_columns , select_mask )
440+ if related_columns :
441+ related_columns , _ = zip (* related_columns , strict = True )
442+
443+ return tuple (selected ) + tuple (map (project_field , related_columns ))
435444
436445 @cached_property
437446 def base_table (self ):
@@ -479,7 +488,11 @@ def get_combinator_queries(self):
479488 # If the columns list is limited, then all combined queries
480489 # must have the same columns list. Set the selects defined on
481490 # the query on all combined queries, if not already set.
482- if not compiler_ .query .values_select and self .query .values_select :
491+ selected = self .query .selected
492+ if selected is not None and compiler_ .query .selected is None :
493+ compiler_ .query = compiler_ .query .clone ()
494+ compiler_ .query .set_values (selected )
495+ elif not compiler_ .query .values_select and self .query .values_select :
483496 compiler_ .query = compiler_ .query .clone ()
484497 compiler_ .query .set_values (
485498 (
0 commit comments