0

cannot make it working I need to annotate with function and for that function I need to pass the instance id

qs = cls.objects.filter(**filters).values(**values).annotate(
            **annotations,
            sheets_sum=counter('sheets'),
            sheets_color=counter('sheets', color=True),
            sheets_grayscale=culc_function(color=False, id = ???),

Is there any way to do it? To get instance id during annotation

  • What is `culc_function`? – Brian Destura Sep 30 '21 at 00:11
  • that is a func that is doing complex query to several related tables and calculations on them and returning calculated value to annotation. To make those queries I need id – Victor Semenov Sep 30 '21 at 06:54
  • Hmm would it be possible to see that? If you do calculations on python level, i don't think it can work this way – Brian Destura Sep 30 '21 at 06:56
  • it is working only if I process queryset two times - getting Id in the middle from already annotated queryset. And that would be totally fine, but the other part of the code (which is not under my control) for whatever reason cannot see double annotated queryset and filters only the first part. – Victor Semenov Sep 30 '21 at 07:16
  • Does this answer your question? [Django custom annotation function](https://stackoverflow.com/questions/30416270/django-custom-annotation-function) – cgl Oct 05 '22 at 21:17

1 Answers1

-1

You can use django's support for expressions (1) and do something like

qs = cls.objects.filter(**filters).values(**values).annotate(
            **annotations,
            sheets_sum=counter('sheets'),
            sheets_color=counter('sheets', color=True),
            sheets_grayscale=culc_function(color=False, id = F('pk'),
)

1: https://docs.djangoproject.com/en/3.2/ref/models/expressions/

codebreach
  • 2,155
  • 17
  • 30
  • I've tried that, I don't know why, but resulting queryset with this F('pk') returns ALL instances, not the one that was annotated – Victor Semenov Sep 30 '21 at 09:22
  • You can't use python functions for annotations, see https://stackoverflow.com/questions/30416270/django-custom-annotation-function . – cgl Oct 05 '22 at 21:18