#31058: Ordering by the result of RawSQL with F expression and distinct
-------------------------------------+-------------------------------------
               Reporter:  wilhelmhb  |          Owner:  nobody
                   Type:  Bug        |         Status:  new
              Component:  Database   |        Version:  2.2
  layer (models, ORM)                |       Keywords:  RawSQL, ordering,
               Severity:  Normal     |  expression
           Triage Stage:             |      Has patch:  0
  Unreviewed                         |
    Needs documentation:  0          |    Needs tests:  0
Patch needs improvement:  0          |  Easy pickings:  0
                  UI/UX:  0          |
-------------------------------------+-------------------------------------
 Hi,
 I run into an exception when combining `RawSQL`, `distinct` and `order_by`
 with an expression:
 {{{
 ids = [10]
 params = (tuple(ids), )
 queryset = Item.objects.annotate(
       score=RawSQL("""
             SELECT SUM(id) AS score
             FROM app_item
             WHERE id IN %s""",
             params=params,
             output_field=FloatField()),
        ).order_by(F("score").desc(nulls_last=True)).distinct()
  print(queryset.query)
 }}}
 where `Item` is any model you want, as I'm only using its `id`.

 The exact exception is: `TypeError: not all arguments converted during
 string formatting`

 The exception seems due to the `sql_with_params` method of
 `django.db.models.sql.Query` duplicating the `params` one time too many :
 a `print(params)` at line 257 in django/db/models/sql/query.py outputs
 `(('10',), ('10',), ('10',))`, while the query has only two placeholders.

 I'm running Django 2.2.6

-- 
Ticket URL: <https://code.djangoproject.com/ticket/31058>
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/052.41365ae7b1edb47f9bd9fea56149b8bf%40djangoproject.com.

Reply via email to