Django 中基于列组合的查询
我想弄清楚如何基于列的组合(例如用户的全名)进行查询,而不需要任何自定义 SQL。这可能吗?
想象一下类似的事情 User.objects.filter(firstname__concat__lastname__startswith="Barack Ob")
我知道在这个特定的示例中,用空格分割“Barack Ob”并修改查询很容易,但是是否可以对像这样的列组成?
I'd like to figure out how to query based on a composition of columns, eg the fullname of a user, without any custom SQL. Is this possible?
Imagine something like
User.objects.filter(firstname__concat__lastname__startswith="Barack Ob")
I know that in this particular example, it'd be easy enough to split "Barack Ob" by whitspace and modify the query, but is it possible to do a query on a composition of columns like this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的数据库支持全文搜索,则可以找到您问题的可能解决方案。我使用 Postgresql (参见文档)并能够执行以下操作查询工作:
您会注意到我在查询中使用了全名。我对文本搜索的了解有限,我不知道是否有一种方法可以实现与
__startswith
等效的功能(使用LIKE
实现)。我怀疑这对于您的需求来说有点过分了。您最好添加自定义字段或自定义方法或两者的组合来实现此目的。
A possible solution to your question can be worked out if your database supports full text search. I use Postgresql (see documentation) and was able to make the following query work:
You will note that I used the full name in the query. My knowledge of text search is limited and I don't know if there is a way to do the equivalent of
__startswith
(implemented usingLIKE
).I suspect that this would be an overkill for your needs. You might be better off adding a custom field or custom method or a combination of the two to implement this.
对于当前的 Django ORM,不,它不存在。您确实可以访问 Q 对象查询处理程序。
With the current Django ORM, no, it doesn't exist. You do have access to the Q object query handler.