两列串联后的Django

两列串联后的Django

本文介绍了两列串联后的Django queryset过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使用两个列的串联来过滤模型?我的模型是这样的:

Is there any way to filter a model using a concatenation of two of its columns? My model is like this:

class Item(models.Model):
    series = models.CharField(max_length=50)
    number = models.CharField(max_length=50)

我需要的是两列连接后进行过滤,如果用户输入A123,我希望能够找到具有系列和数字的任何项,例如%A和123%或%A1和23%
使用django是否可以楷模?还是有可能使用原始sql?
我宁愿不使用连接来构造新列。

What I need is to filter after the concatenation of the two columns, if a user inputs A123 I want to be able to find any Item that has series and number like %A and 123% or %A1 and 23%Is this possible using the django models? Or is it possible with raw sql?I would rather not construct a new column with the concatenation.

推荐答案

是的,这是可能的。您将需要用字段的串联来注释 QuerySet,并且新的虚拟列将能够进行过滤。

Yes that is possible; you will need to annotate the QuerySet with the concatenation of the fields, and that new "virtual" column will be capable of filtering.

using Concat as an annotation function

这篇关于两列串联后的Django queryset过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 17:52