Search code examples
djangodjango-modelsdjango-querysetdjango-annotate

How to annotate Django Queryset with the same value but with a different data type of one of existing fields?


I have a Django model that has a NumberVal field which is models.FloatField().

Then I need to annotate the queryset objects like so .annotate(numberval_as_text=str(OuterRef("NumberVal"))) - the same value, but as a string except for the fact that this throws QuerySet.annotate() received non-expression(s): OuterRef(NumberVal) error which is clearly right but it demonstrates the point.

I need this because this annotation is followed by an extensive second annotation where I need this numberval_as_text in subquery filters.

Any hint would be appreciated.


Solution

  • Calling str on an object obviously will give you a string representation of the object, hence you get the error. If one wants to type case something, they can use the Cast database function [Django docs]:

    from django.db.models import CharField
    from django.db.models.functions import Cast
    
    
    queryset.annotate(numberval_as_text=Cast(OuterRef("NumberVal"), output_field=CharField(max_length=256)))
    

    Note: Unless this annotation is in a subquery, you want to use F("NumberVal") (from django.db.models import F) instead of OuterRef("NumberVal")