草庐IT

python - Django : Joining two tables and using extra field from second table for order_by

coder 2023-10-26 原文

我有两个模型A,B

Mysql查询是

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

//这里b.value是longtext字段,所以加0转换成Integer,然后排序。

我需要同样的 Django 查询。

我试过了

A.objects.filter(b__key ="vcount",type = "abc",status = "done").order_by('-b__value')[:5]  

但上面的 Django 查询给出了错误的结果,因为它是按 Ascii 值排序

因此需要将 'value' 字段转换为 Integer 然后需要对其进行排序。

我也尝试了下面的一个但是给出了错误

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]

建议或帮助将不胜感激。

最佳答案

.extra()方法的select是带SQL的,所以列名要写成SQLb.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]

关于python - Django : Joining two tables and using extra field from second table for order_by,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36737451/

有关python - Django : Joining two tables and using extra field from second table for order_by的更多相关文章

随机推荐