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

Is there a way to annotate django query with non-expression?

我有一个用例,我需要获取所有对象,其中 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

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

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

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

对于那些仍然面临新版本 Django 问题的人,将不得不使用 ExpressionWrapper 并且可能 F

from django.db.models import ExpressionWrapper, F
MyModel.objects.annotate(annotated_field=ExpressionWrapper(Value('some string', output_field=CharField()))).filter(annotated_field__startswith=F('existing_field'))