Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django annotate model custom method

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 ) 
like image 971
Wreeecks Avatar asked Sep 18 '25 11:09

Wreeecks


2 Answers

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

like image 188
JPG Avatar answered Sep 21 '25 23:09

JPG


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.

like image 31
HoneyNutIchiros Avatar answered Sep 21 '25 23:09

HoneyNutIchiros