﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
31058	Ordering by the result of RawSQL with F expression and distinct.	wilhelmhb	nobody	"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"	Bug	closed	Database layer (models, ORM)	dev	Normal	duplicate	RawSQL, ordering, expression		Unreviewed	0	0	0	0	0	0
