Fred Collins
Fred Collins

Reputation: 5010

Django search in the database

I use MySQL for the production server and SQLite for the testing local server for my django application.

I've a model like this:

class Product(models.Model):
    name = models.CharField(max_length = 40)

I've implemented a search feature in my application for searching product. I use this command: Product.objects.filter(name__contains = text)

But in this way, if I search a white space " ", the application returns me every product with a space in the name. It's a bit ugly, and also if I search a single char, for example a it returns all name that contains a. Is there a way to search only 'single full word'?

Upvotes: 1

Views: 1686

Answers (1)

S.Lott
S.Lott

Reputation: 391992

https://docs.djangoproject.com/en/1.3/ref/models/querysets/#regex

http://docs.python.org/library/re.html

pattern= r"\b%s\b" % text
Product.objects.filter(name__regex = pattern)

Upvotes: 3

Related Questions