2

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.

Maarten Ureel
  • 393
  • 4
  • 18

1 Answers1

2

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?

Patti
  • 186
  • 3
  • 7
  • Django's [extra function](https://docs.djangoproject.com/en/2.1/ref/models/querysets/#extra) is exactly what I need indeed! – Maarten Ureel Jun 24 '18 at 09:14