问题描述
我有一个我想用搜索字词过滤的模型,通常是一个名字。但是在我的数据库中, first_name
和 last_name
是两个单独的字段。 例如
search_term ='Will Sm'
db_persons
record: first_name ='Will',last_name ='Smith'
搜索字词将能够检索此记录。
如何实现?
db_persons.objects.filter(__?__)
更新:
寻找一种方法来连接字段并查询没有原始sql的连接结果
一个简单的解决方案是在模型上添加另一个字段 complete_name
。在保存
,您将通过连接 first_name
和 last_name
没有任何空格的字段(您需要从连接结果中删除所有空格)。然后,您将使用 search_term
在这个字段上进行查询,但空格也将被剥离。
简单的例子给出你的一般想法:
class Person(models.Model):
first_name = CharField(...)
last_name = CharField(...)
complete_name = CharField(...)
def save(self,* args,** kwargs):
complete_name = '%s%s'%(self.first_name,self.last_name)
self.complete_name = complete_name.replace('','')
super(Person,self).save(* args, ** kwargs)
results = Person.objects.filter(complete_name__icontains = search_term.replace('',''))
I have a model I want to filter with a search term, which is usually a name. However in my database first_name
and last_name
are two separate fields.
e.g.
search_term = 'Will Sm'
db_persons
record: first_name = 'Will', last_name = 'Smith'
the search term would be able to retrieve this record.
How can I achieve that?
db_persons.objects.filter(__?__)
UPDATE:
Looking for a way to concatenate fields and querying the concatenated result without raw sql
A simple solution will be to add another field complete_name
on your model. On save
you will update this field by concatenate first_name
and last_name
fields without any space (you need to strip all spaces from the concatenation result). Then you will do your query on this field with the search_term
but with spaces also stripped.
Simple example to give you the general idea:
class Person(models.Model):
first_name = CharField(...)
last_name = CharField(...)
complete_name = CharField(...)
def save(self, *args, **kwargs):
complete_name = '%s%s' % (self.first_name, self.last_name)
self.complete_name = complete_name.replace(' ', '')
super(Person, self).save(*args, **kwargs)
results = Person.objects.filter(complete_name__icontains=search_term.replace(' ', ''))
这篇关于django查询过滤器问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!