How to annotate the result of a model method to a django queryset

7.7k views Asked by At

From the django docs on annotate():

Annotates each object in the QuerySet with the provided list of query expressions. An expression may be a simple value, a reference to a field on the model (or any related models), or...

Is it possible to annotate the results of a method for the model?

I've tried like this:

my_queryset.annotate(ann=my_method(request.user))

and

my_queryset.annotate(my_method(request.user))

But I get an error that my_method is not defined. The method exists and works fine normally: object.my_method(request.user)

I think there is a decorator to have a method treated like a field, but I can't seem to find any info on that (it might have been for django template based method calls, so possibly not related)

An alternate solution is provided in this question. But I would like to know if it is possible to annotate method results.

1

There are 1 answers

0
Anshu Rani On

This question is very old but I want to answer it, as it may be helpful for someone like me searching for the answers basically, I tried a lot of ways to do it, but there is no direct way to do it, the workaround I figured out is after making the initial basic query like
my_queryset = myModelClass.objects.annotate(ann = Value(False, output_field = models.BooleanField() )).all()
/# added an extra field filled with default value, then looped through the /# returned query set and call the model method like below

for record in my_queryset :
record.ann = cqa.my_method(request.user)

Thank you