Django object filter - price behaving strangely, eg 170 treated as 17 etc

北战南征 提交于 2019-12-04 21:23:24

The problem, as Jeff suggests, is that price is a CharField and thus is being compared using character-by-character string comparison logic, i.e. any string of any length starting with 1 will be less than any string of any length starting with 2, etc.

I'm curious what problems you were having with having price be an IntegerField, as that would seem to be the straightforward solution, but if you need to keep price as a CharField, here's a (hacky) way to make the query work:

lt = 200
gt = 10
qs = Product.objects.extra(select={'int_price': 'cast(price as int)'},
                           where=['int_price < %s', 'int_price > %s'],
                           params=[lt, gt])
qs.all()  # the result

This uses the extra method of Django's QuerySet class, which you can read about in the docs here. In a nutshell, it computes an integer version of the string price using SQL's cast expression and then filters with integers based on that.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!