'Is there a way to annotate django query with non-expression?
I have use case where I need to get all objects where existing_field is the beginning of some string.
some string changes dynamically so I need a smart way to filter out objects.
My idea is to create annotated query like this:
MyModel.objects.annotate(annotated_field='some string').filter(annotated_field__startswith=F('existing_field'))
Currently it is failing with:
QuerySet.annotate() received non-expression(s): some string
Is there a way to annotate objects with string value?
Solution 1:[1]
For those who are still facing the problem with newer versions of Django will have to use ExpressionWrapper and probably 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'))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | rahulg |
