Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: filtering queryset by "parameter has part of field's value"?

I have a simple model:

class Place(models.Model):
    name = models.CharField()

and it has some representative names like Starbucks, McDonald's, etc. as shown below.

 id |   name   
----+----------
  1 | Starbucks
  2 | McDonald's
  3 | ...  

And I also have some place names as query parameter, for example:

  • Starbucks Pike Place
  • McDonald's Sand Lake Road
  • Another Starbucks Out There

What I'm trying to achieve is to filter/get appropriate Place object with given parameters, determine whether it has part of place's name.

How can I do this with django's QuerySet API?
Have checked references and forum to find something like below but was no luck:

Place.objects.get(name__ispartof=PARAM)
# or
Place.objects.get(PARAM__contains=Q('name'))

In Postgres, my case may equivalent to:

SELECT id FROM table
WHERE 'Starbucks Pike Place' LIKE CONCAT('%', name, '%')

Should I have to perform a raw() SQL query for this?

Thanks in advance.

like image 299
akwataip Avatar asked Dec 07 '25 05:12

akwataip


1 Answers

I think I've found a horrible way to do it in the ORM without needing raw SQL. Hopefully someone else will be able to find something better.

from django.db.models import ExpressionWrapper, CharField, Value, F

param = 'Starbucks Pike Place'
myparam = ExpressionWrapper(Value(param), output_field=CharField())
Place.objects.annotate(param=myparam).filter(param__contains=F('username'))
like image 78
wim Avatar answered Dec 08 '25 18:12

wim