2

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.

9
  • any specific reason to cast to int?? Commented Aug 18, 2015 at 9:49
  • if "my_id" is 100, it will not select the row with "000100" Commented Aug 18, 2015 at 9:50
  • casting is not needed if it "works" without. I saw other questions where __contains was used, but this will not work, as a row could have "100100" as building field value. Commented Aug 18, 2015 at 9:51
  • simply writing int(string with prefixed 0) automatically converts it to a real number Commented Aug 18, 2015 at 9:55
  • 1
    I would argue that it's ugly or hacky. The purpose of extra, according to django docs is to add a hook for injecting specific clauses into the SQL generated by a QuerySet., there's always some cases that orm doesn't cover enough. Beware though, if you change your database backend the raw query might not work. Commented Aug 18, 2015 at 15:21

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

Comments

-3

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

4 Comments

I already have a real int (that was cast, as you propose), that needs to filter my django queryset. The problem is the value in the db: it is "000100", and if I just do a Address.objects.filter(building=myfiltervalue), it doesnt not filter as I want (0 results)
myfiltervalue value is what?
I think @benzkji is asking for how to create a proper query, not how to convert between int and str.
yes got it .. i am still looking for the solution.. @ShangWang: do you have any idea ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.