I have two models A, B
Mysql query is
SELECT a.ID FROM a INNER JOIN b ON ( a.ID = b.id ) WHERE ( b.key = 'vcount' ) AND (a.type = 'abc') AND (a.status = 'done') ORDER BY b.value+0 DESC LIMIT 0, 5
//Here b.value is longtext field, so added 0 to convert to Integer, then sorted.
I need Django query for the same.
I have tried this
A.objects.filter(b__key ="vcount",type = "abc",status = "done").order_by('-b__value')[:5]
but above Django query is giving wrong result, since it is sorting by Ascii value
So need to convert 'value' field to Integer then need to sort it.
I also tried below one but giving errors
xyz = A.objects.filter(b__key ="vcount",type = "abc",status = "done").extra(select={'value_int': "CAST(b__value AS UNSIGNED)"}).order_by('-value_int')[:5]
Suggestions or Help will be appreciated.
The .extra()
method's select
takes SQL, so the column name should be written as SQL b.value
.
xyz = A.objects.filter(b__key ="vcount",type = "abc",status = "done")
.extra(select={'value_int': "CAST(b.value AS UNSIGNED)"})
.order_by('-value_int')[:5]
Since I'm pretty sure this is the issue I'm going to write it anyway...
I'm guessing that value
is a DecimalField
which is stored internally as a string for indexing, which is why you are seeing strange ordering.
The solution is to change the type of value from DecimalField
to FloatField
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.