2

I'm trying to convert UUIDs to integers within an annotate.

So like:

Item.objects.values_list('pk', flat=True).annotate(
    int_of_pk=int('pk')
)

which throws error:

ValueError: invalid literal for int() with base 10: 'pk'

or like:

from django.db.models import IntegerField
from django.db.models.functions import Cast

Item.objects.values_list('pk', flat=True).annotate(
    int_of_pk=Cast('pk', output_field=IntegerField())
)

which throws error:

File "/path/ve/lib/python3.7/site-packages/django/db/backends/utils.py", line 84, in _execute
    return self.cursor.execute(sql, params)
psycopg2.errors.CannotCoerce: cannot cast type uuid to integer
LINE 1: ...em"."uuid", ("item"."uuid")::integer ...
                                      ^

Any ideas pop out at you?

Sunderam Dubey
  • 1
  • 11
  • 20
  • 40
SpencerF2
  • 21
  • 2
  • Is there a particular reason you need to do this in an annotation and can't do the conversion afterwards? – Iain Shelvington Jun 29 '22 at 00:33
  • @IainShelvington Yes. The integer that results will be converted to a string and then a string comparison will take place with the aim of returning the matching object. This operation will happen a lot and the annotation will be faster. Thanks for thinking about it! – SpencerF2 Jun 29 '22 at 19:30

0 Answers0