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'))
Place.objects.get(name__contains=PARAM)
should do it. Note that you can also use icontains
instead of contains
if you'd like the query to be case-insensitive.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.