1

I am trying to slice the last two characters of a field and annotate it to query result, using the method given in this post. Something like:

Person.objects.all()\
.annotate(
    code = Substr('str', 1, -2),
)

The above code returns an empty string as soon as I use negative values as the third argument. How can I achieve this?

Azee
  • 329
  • 6
  • 20

1 Answers1

1

You need to annotate a field for a positive index at first. Then you can use the Substr as follows:

Person.objects.annotate(
    PositiveIndex=ExpressionWrapper(Length('str') - 1, output_field=CharField()),
    code=Substr('str', F('PositiveIndex'))
).values('code')
Happy Ahmad
  • 1,072
  • 2
  • 14
  • 33
  • 1
    Thanks, it worked, however no ExpressionWrapper was needed since both length and -1 are integer. @Ahmad By the way, for those who want to implement, it should be done in two separate annotations. – Azee Jan 07 '18 at 06:15