在Django中查询全名 [英] Querying full name in Django

查看:125
本文介绍了在Django中查询全名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何查询Django中的全名?

How can I query on the full name in Django?

为了澄清,我本来希望创建一个临时列,结合first_name和last_name来给出一个全名,然后这样做一样,如下所示:

To clarify, I essentially want to do create a temporary column, combining first_name and last_name to give a fullname, then do a LIKE on that, like so:

select [fields] from Users where CONCAT(first_name, ' ', last_name) LIKE '%John Smith%";

上述查询将返回名为John Smith的所有用户可能我想避免使用原始的SQL调用。

The above query would return all users named John Smith. If possible I'd like to avoid using a raw SQL call.

我正在谈论的模型是库存django.contrib.auth.models用户模型。直接对模型的更改不是一个问题。

The model I'm talking about specifically is the stock django.contrib.auth.models User model. Making changes to the model directly isn't a problem.

例如,如果用户要搜索John Paul Smith,则应该将其与名字匹配约翰·保罗和姓氏史密斯,以及名字约翰和姓氏保罗·史密斯的用户。

For example, if a user was to search for 'John Paul Smith', it should match users with a first name of 'John Paul' and last name 'Smith', as well as users with first name 'John' and last name 'Paul Smith'.

推荐答案

除非我缺少某些东西,否则可以使用python查询您的数据库,如下所示:

Unless I'm missing something, you can use python to query your DB like so:

from django.contrib.auth.models import User
x = User.objects.filter(first_name='John', last_name='Smith') 

编辑: strong>
要回答您的问题:

To answer your question:

如果您需要返回John Paul Smith,当用户搜索John Smith时,您可以使用 包含,转化为SQL LIKE 。如果您只需要存储名称John Paul的容量,则将这两个名称放在first_name列中。

If you need to return 'John Paul Smith' when the user searches for 'John Smith' then you can use 'contains' which translates into a SQL LIKE. If you just need the capacity to store the name 'John Paul' put both names in the first_name column.

User.objects.filter(first_name__contains='John', last_name__contains='Smith') 

这转换为:

SELECT * FROM USERS
WHERE first_name LIKE'%John%' 
AND last_name LIKE'%Smith%'

这篇关于在Django中查询全名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆