4

I wanted to use the custom method value and compute it. Is it possible to annotate model's custom methods? If yes, can you give an example. Thanks in advance!

Model

class Project(model.models):

    project_name = models.CharField(
        _('Project name'),
       max_length=255,
       blank=True,
       null=True,
   )

   def custom_method(self):
       return 100

Query

qs = Project.objects.annotate(new_val=F('custom_method')  * 1.5 ) 
Wreeecks
  • 2,186
  • 1
  • 33
  • 53

2 Answers2

7

No. Anything that goes through a built-in manager has to be a real field since they only touch the database. In order to work with a custom field/property they'd have to turn every record in the table into a model, then filter through them in Python.

Source : Django - Can you use property as the field in an aggregation function?

If you trying to annotate as you mentioned, you'll get a FieldError as below,

FieldError: Cannot resolve keyword 'custom_method' into field. Choices are: project_name



In short, you can do annotation only with the actual db attributes/fields

JPG
  • 82,442
  • 19
  • 127
  • 206
  • Thanks for your quick response and explanation. Then i have to loop the queryset in order to use custom method's value. – Wreeecks Apr 18 '18 at 02:09
3

I believe you must evaluate the queryset first. So once you do:

for i in qs:
    return i.custom_method * 1.5

with a Product.objects.all() queryset, then it should work.

HoneyNutIchiros
  • 541
  • 3
  • 9
  • Thanks for your reply. This is what I have now. I want to compute the values without resorting to loop, just filter/annotate. – Wreeecks Apr 18 '18 at 02:01
  • Yeah I don't think you can do anything with the custom method using a normal filter/annotate Django query, as the custom method is not technically in the database. It is just called once the queryset is evaluated. I am not sure your reasons for using the custom method, but you could just write an annotate statement that multiplies your column of choice by 1.5? Have you thought about those types of options? – HoneyNutIchiros Apr 18 '18 at 05:45
  • it's a bit complicated in terms of computation, there's more computation to be done. I've only given a basic example. Anyway, thanks for your response. – Wreeecks Apr 18 '18 at 05:51