#30658: Unexpected result using union on two querysets with one annotating a 
column
-------------------------------------+-------------------------------------
               Reporter:  Stefan     |          Owner:  nobody
  Wehrmeyer                          |
                   Type:  Bug        |         Status:  new
              Component:  Database   |        Version:  2.2
  layer (models, ORM)                |
               Severity:  Normal     |       Keywords:
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 I have two models:

 {{{
 class ModelA(models.Model):
     column_a = models.CharField(max_length=255, blank=True)
     column_b = models.CharField(max_length=255, blank=True)


 class ModelB(models.Model):
     column_b = models.CharField(max_length=255, blank=True)

 }}}

 I want to query both at once using `union`, filling in a default value for
 `column_a` in `ModelB`:


 {{{
 from django.db.models import Value, CharField

 ModelA.objects.create(
     column_a='a',
     column_b='b',
 )
 ModelB.objects.create(
     column_b='b',
 )

 columns = ('column_a', 'column_b')

 a_qs = ModelA.objects.all().values(*columns)
 b_qs = (
     ModelB.objects.all()
     .annotate(
         column_a=Value("a", output_field=CharField())
     )
     .values(*columns)
 )
 qs = a_qs.union(b_qs)
 qs
 }}}

 This leads to the following unexpected output:

 {{{
 <QuerySet [{'column_a': 'a', 'column_b': 'b'}, {'column_a': 'b',
 'column_b': 'a'}]>
 }}}

 Note that the second row in the result (coming from `b_qs`) has the values
 for the columns mixed up!

 The SQL query is:
 {{{
 print(qs.query)
 SELECT "example_modela"."column_a", "example_modela"."column_b" FROM
 "example_modela" UNION SELECT "example_modelb"."column_b", a AS "column_a"
 FROM "example_modelb"
 }}}

 I'm not sure if I'm using the ORM in a wrong way. I would consider my use
 case (=union+annotate) valid and would expect some kind of error if the
 ORM was not able to deal with it.

-- 
Ticket URL: <https://code.djangoproject.com/ticket/30658>
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 view this discussion on the web visit 
https://groups.google.com/d/msgid/django-updates/050.c58a8289107e7b16e8cd4c85aae6b400%40djangoproject.com.

Reply via email to