有没有办法用非表达式注释 django 查询?

Posted

技术标签:

【中文标题】有没有办法用非表达式注释 django 查询?【英文标题】:Is there a way to annotate django query with non-expression? 【发布时间】:2020-02-13 02:17:58 【问题描述】:

我有一个用例,我需要获取existing_fieldsome string 开头的所有对象。

some string 动态变化,因此我需要一种智能方法来过滤掉对象。

我的想法是像这样创建带注释的查询:

MyModel.objects.annotate(annotated_field='some string').filter(annotated_field__startswith=F('existing_field'))

目前它失败了: QuerySet.annotate() received non-expression(s): some string

有没有办法用字符串值注释对象?

【问题讨论】:

【参考方案1】:

不确定您在问什么,但请尝试Value 表达式。

MyModel.objects.annotate(annotated_field=Value('some string', output_field=CharField())).filter(annotated_field__startswith=F('existing_field'))

【讨论】:

非常感谢。像你说的那样同时解决了它,但首先注释然后过滤。需要先创建annotated_field

以上是关于有没有办法用非表达式注释 django 查询?的主要内容,如果未能解决你的问题,请参考以下文章