2

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.

2 Answers 2

3

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")

Sign up to request clarification or add additional context in comments.

Comments

1

You don't need to use OuterRef. You can just use plain cast with annotation.

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


qs.annotate(numberval_as_text=Cast('NumberVal', output_field=models.CharField()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.