Opened 4 months ago

Last modified 4 months ago

#31496 new Bug

Combined queryset crash when chaining `values()` after `order_by()` with annotated constantants.

Reported by: GardenLee Owned by: nobody
Component: Database layer (models, ORM) Version: 3.0
Severity: Normal Keywords:
Cc: Hasan Ramezani Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no


When i tried query with 'annotate', 'union', 'order_by('annotate_field')' and 'values' at the same time, i got AttributeError('NoneType' object has no attribute 'split')

# 1. make 2 query_set
qs1 = Foo.objects.annotate(bar_val=Value(1, output_field=IntegerField())).filter(bar=False)
qs2 = Foo.objects.annotate(bar_val=Value(2, output_field=IntegerField())).filter(bar=True)

# 2. union
qs3 = q1.union(q2)

# 3. order_by annotate field
qs4 = q3.order_by('bar_val')

# 4. get values

In this case, I confirmed ('id', None) tuple passed by compiler.query.set_values() in django/db/models/sql/

Change History (3)

comment:1 Changed 4 months ago by felixxm

Summary: When using 'annotate', 'union', 'order_by('annotate_field')' and 'values' at the same time, error occurredCombined queryset crash when chaining `values()` after `order_by()` with annotated constantants.
Triage Stage: UnreviewedAccepted

Thanks for this ticket. This code was changed in 2cbd3967e0a51eab993df89679046d25ec78baec, however previously it raised DatabaseError so IMO it's not a release blocker. We can consider backporting if patch will be straightforward.

comment:2 Changed 4 months ago by Hasan Ramezani

I take a look and here is my understanding:

In this case, when we order queryset by annotated value(bar_val) the src variable, has type <class 'django.db.models.functions.comparison.Cast'> and is None.
So, add_select_col function adds None to values_select.

we should somehow add bar_val to the values_select.

@felixxm, If you have any workaround, I can prepare a patch.

comment:3 Changed 4 months ago by Hasan Ramezani

Cc: Hasan Ramezani added
Note: See TracTickets for help on using tickets.
Back to Top