Python – Django: Filter the set of queries by the value of “parameter has part of field'”?

Django: Filter the set of queries by the value of “parameter has part of field'”?… here is a solution to the problem.

Django: Filter the set of queries by the value of “parameter has part of field'”?

I have a simple model :

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

There are also some more representative names, such as Starbucks, McDonald's, etc., as shown below.

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

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

  • Starbucks Parker stores
  • McDonald’s Sand Lake Road
  • Another Starbucks

What I want to achieve is filtering/getting the appropriate Place object with the given parameters, determining if it contains part of the name of the place.

How do I do this using Django’s QuerySet API?
Check quotes and forums to find something like the following, but no luck:

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

In Postgres, my case might be equivalent to:

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

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

Thanks in advance.

Solution

I

think I’ve found a terrible way to do this in ORM without raw SQL. Hopefully, others will 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'))

Related Problems and Solutions