4

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?

2 Answers 2

18

Not sure what you're asking but try Value expression.

MyModel.objects.annotate(annotated_field=Value('some string', output_field=CharField())).filter(annotated_field__startswith=F('existing_field'))
Sign up to request clarification or add additional context in comments.

1 Comment

Great thanks. Solved it in the meantime like you said but first annotated then filtered. annotated_field needs to be created first.
2

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'))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.