Search code examples
djangodjango-querysetdjango-annotate

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

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