QuerySet.union() crashes with IndexError when getting cached results.
    
    
    
      
      
      
        
I tried 4.2a1 today on my project and I noticed pagination was broken on one view.
After little investigation I manage to reproduce an error:
Event is a model with set a Foreignkey 
>> events = Event.objects.all()
>> events_without_set = events.filter(set__isnull=True)
>> one_event_of_each_set = (
        events.filter(set__isnull=False)
               .order_by("set_id")
               .distinct("set_id")
)
>> my_list = events_without_set.union(one_event_of_each_set)
>> my_list.count()
212
>> my_list[2]
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/venv/lib/python3.11/site-packages/django/db/models/query.py", line 450, in __getitem__
    return qs._result_cache[0]
           ~~~~~~~~~~~~~~~~^^^
IndexError: list index out of range
With django 4.1.5 my_list[2] returns an event.
       
     
   
 
      
        
        
          Change History
          (11)
        
          
  
  
  
    
      | Description: | 
      
        modified (diff)
       | 
    
  
 
           
          
  
  
  
    
      | Component: | 
      
        Uncategorized → Database layer (models, ORM)
       | 
    
  
 
           
          
  
  
  
    
      | Cc: | 
      
        Simon Charette added
       | 
    
    
      | Severity: | 
      
        Normal → Release blocker
       | 
    
    
      | Summary: | 
      
        Error with Union queryset not being paginable → QuerySet.union() crashes with IndexError when getting cached results.
       | 
    
    
      | Triage Stage: | 
      
        Unreviewed → Accepted
       | 
    
  
 
           
          
  
  
  
    
      | Owner: | 
      
        changed from nobody to Francesco Panico
       | 
    
    
      | Status: | 
      
        new → assigned
       | 
    
  
 
           
          
          
          
  
  
  
    
      | Patch needs improvement: | 
      
        set
       | 
    
  
 
           
          
  
  
  
    
      | Patch needs improvement: | 
      
        unset
       | 
    
  
 
           
          
  
  
  
    
      | Triage Stage: | 
      
        Accepted → Ready for checkin
       | 
    
  
 
           
          
  
  
  
    
      | Resolution: | 
      
        → fixed
       | 
    
    
      | Status: | 
      
        assigned → closed
       | 
    
  
 
           
          
          
         
       
     
        
    
    
Thanks for testing the alpha release!
Regression in 3d734c09ff0138441dfe0a59010435871d17950f.