Maarten Ureel
Maarten Ureel

Reputation: 475

Search by contents of integer field in Django

I have a table containing a list of phone prefixes, stored as integers. However I want to be able to search in those in a 'contains' way, so e.g. when searching for '32' I would like to see all records that contain the actual text '32' in the prefix.

That is no problem if using plain SQL of course, but I can't find any guidance on how to accomplish this in Django.

Basically the part that matters is now:

if search_value:
    destinations = destinations.filter(description__icontains=search_value)

And it would have to be something like:

if search_value:
    destinations = destinations.filter(description__icontains=search_value, prefix__icontains=search_value)

However, since 'prefix' is an integer column, this does not yield any results.

What is the best approach for this? I was thinking of a generated field in MySQL, but then again I don't know how to make that field available in the Django model.

Upvotes: 2

Views: 3608

Answers (1)

Patti
Patti

Reputation: 186

I think what you need to do is to CAST the prefix field as a CHAR and then filter against the CAST version of the field.

Take a look at this stackoverflow question:

How do i cast char to integer while querying in django ORM?

Upvotes: 2

Related Questions