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

[亡魂溺海] 提交于 2019-12-06 14:50:16

问题


I have a simple object filter that uses price__lt and price__gt. This works on a property on my product model called price, which is a CharField [string] (decimal saw the same errors, and caused trouble with aggregation so reverted to string).

It seems that when passing in these values to the filter, they are treated in a strange way, eg 10 is treated as 100. for example:

/products/price/10-200/ returns products priced 100-200. the filters are being passed in as filterargs: FILTER ARGS: {'price__lt': '200', 'price__gt': '10'} . This also breaks in the sense that price/0-170 will NOT return products priced at 18.50; it is treating the 170 as 'less than 18' for some reason.

any idea what would cause this, and how to fix it? Thanks!


回答1:


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.



来源:https://stackoverflow.com/questions/11843342/django-object-filter-price-behaving-strangely-eg-170-treated-as-17-etc

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