Django Queryset: Cast VARCHAR field in SQL before filtering

拟墨画扇 提交于 2019-12-02 12:58:05

问题


I have a table that I cannot control, but need to select from it. The field "building" is a varchar, and also defined like this in my (non managed) django model. But it should be treated as integer, when selecting from that table (there are values like "000100", and even spaces at the end).

I need a simple filter like this:

.annotate(CastInt("building")).filter(building__castint__exact=my_id)

only problem is, CastInt does not exist. How could one achieve this? I was looking at .extra() (that we should no use anymore, as it's deprecated) and RawSQL, but hoping for a solution using only the Django ORM, without custom written SQL?

EDIT: currently using a hack from here (in the comments):

Address.objects.extra(where=('CAST(TRIM(building) AS UNSIGNED)=%s',),
                      params=(building_no, ))

works, but ugly.

EDIT II: See my accepted answer - using my second best friend, the regex.


回答1:


as simple as it gets: use a regex query

regex = r'^0{0,4}%s ?$' % building_no
address = Address.objects.filter(building__iregex=regex)\

any hints on performance welcome...




回答2:


try simple int(you string value)

for example:

str = "00100"
int(str)

will give 100 as integer value. same applies for

 str = "100100"
int(str)

gives 100100 as integer



来源:https://stackoverflow.com/questions/32068949/django-queryset-cast-varchar-field-in-sql-before-filtering

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