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:
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.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With