8

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.

Community
  • 1
  • 1
43Tesseracts
  • 4,617
  • 8
  • 48
  • 94
  • 3
    Possible duplicate of [Django custom annotation function](http://stackoverflow.com/questions/30416270/django-custom-annotation-function) – 2ps Dec 28 '16 at 03:25

1 Answers1

1

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

Anshu Rani
  • 21
  • 1