Baz
Baz

Reputation: 13135

Filter Model Object using Wild-Chars

I need to be able to filter using wildchars, for example:

Surnames.objects.filter(surname="GR%FF%N")

should return objects with the following surnames: GRIFFIN, GREFFTEN, GRAFFAIN, and so on. Now obviously filter doesn't recognise % as a wildchar but the code above should demonstrate what I need to do. I also wish to limit the number of results returned. How would you recommend I do this?

Upvotes: 0

Views: 50

Answers (2)

user12065892
user12065892

Reputation:

There are lots of way to filter on Django that supports your database.

For wildcard query, you do like this:

Surnames.objects.filter(surname__icontain="YOUR QUERY TERM")
Surnames.objects.filter(surname__contain="YOUR QUERY TERM")

above one are case sensitive and another case-insensitive

Also there are some other lookup that you help you to get your job done:

startswith endswith istartswith iendswith

Also, you can query by regex patter with regex lookup.

Bellow i showed you how you can your job done:

Surnames.objects.filter(surname__regex="YOUR REGEX PATTERN")
Surnames.objects.filter(surname__startswith="YOUR QUERY TERM")
Surnames.objects.filter(surname__iendswith="YOUR QUERY TERM")
Surnames.objects.filter(surname__istartswith="YOUR QUERY TERM")

Upvotes: 1

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476740

You can wwork with a regular expression by making use of the __regex lookup [Django-doc]:

Surnames.objects.filter(surname__regex='^GR.*FF.*N$')

You can limit the number of results by slicing the queryset:

Surnames.objects.filter(surname__regex='^GR.*FF.*N$')[:20]

here we thus return the first 20 results. Since we did not use .order_by() it can return items in any order.

Upvotes: 2

Related Questions