问题
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