3

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?

makozaki
  • 3,772
  • 4
  • 23
  • 47

2 Answers2

16

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'))
makozaki
  • 3,772
  • 4
  • 23
  • 47
kyore
  • 812
  • 5
  • 24
  • 1
    Great thanks. Solved it in the meantime like you said but first annotated then filtered. `annotated_field` needs to be created first. – makozaki Oct 16 '19 at 11:32
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'))
rahulg
  • 2,183
  • 3
  • 33
  • 47