I have a simple address book app that I want to make searchable. The model would look something like:
class Address(models.Model):
address1 = models.CharField("Address Line 1", max_length=128)
address2 = models.CharField("Address Line 2", max_length=128)
city = models.CharField("City", max_length=128)
state = models.CharField("State", max_length=24)
zipCode = models.CharField("Zip Code", max_length=24)
def __unicode__(self):
return "%s %s, %s, %s, %s" % (self.address1, self.address2, self.city, self.state, self.zipCode)
class Entry(models.Model):
name = models.CharField("Name of Business", max_length=128)
createdBy = models.ForeignKey(User)
address = models.ForeignKey(Address, unique=True)
def __unicode__(self):
return "%s - %s, %s" % (self.name, self.address.city, self.address.state)
I want the searching to be fairly loose, like: Bank of America Los Angeles 91345
. It seems like I want a field that contains all of those elements into one that I can search, but that also seems redundant. I was hoping I could add a method to the Entry model like开发者_Python百科 this:
def _getSearchText(self):
return "%s %s %s" % (self.name, self.address, self.mascot)
searchText = property(_getSearchText)
...and search that as a field, but I suppose that's wishful thinking... How should I approach this using basic Django and SqLite (this is a learning exercise).
Thank you!!
If you're doing anything more than extremely basic searching, you want a proper full-text database search engine.
Something like django-sphinx might be the answer. http://github.com/dcramer/django-sphinx
If you're really only doing it to mess with django, one extremely simple solution is to pull all the results and use a regex to figure out your matches. Obviously this is a terrible solution.
A better solution would be to create a filter adding your search terms onto a query programmatically.
https://docs.djangoproject.com/en/dev/ref/models/querysets/#filter
https://docs.djangoproject.com/en/dev/ref/models/querysets/#contains
精彩评论