Method for matching multiple keywords using objects. filter of method of django

  • 2021-07-22 10:07:58
  • OfStack

Introduction:

Today, when using django, I suddenly want to use how to match multiple keywords. We know that django has an objects. filter () method. We can match the article name of title containing key keywords in the database through the following code.


table.objects.filter(title__contains=key)

Question:

But my requirement is that I need to match more than one keyword article but more than one keyword article, so how do we use objects. filter () of django?


table.objects.filter(title__contains=key1)+.objects.filter(title__contains=key2)+....?

Resolve:

We all know that in a normal sql statement, we can do this if we need to match title with multiple keywords


select title from data where title regexp 'key1|key2'
select title from data where title like '%key1%' or like '%key2%'

The above two sql statements select all articles with key1 and key2 in title attributes, so will django also have one way to match multiple keywords? Of course, there is the following code


from django.db.models import Q
table.object.filter(Q(title__startswith='key1') | Q(title__startswith='key2'))

First import the Q method of django and then add the corresponding match in filter


Related articles: