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 )
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With