2 years ago

#74886

test-img

Reactoo

correct use of class method in django

I had studied class methods in python but never really understood its application in Djnago. My coding life was going well without the use of it. But I came across a situation where class method will be useful.

My model:

class Example(models.Model):
    post_count = models.IntegerField(default=0)


@classmethod
def total_counts(cls):
    return cls.objects.values('post_views').annotate(sum logic)

In the above function, if I had used property decorator, i can only get a single object post_count because the object self is used. But if I use classmethod then I can count the post views of all the objects.

So my thought is that whenever we have to deal with all the objects instead of a self object we need class method. Is this correct?

Also, can we use this class method directly into our model serializer field just like we use property to serializer??

django

django-models

django-rest-framework

python-decorators

class-method

0 Answers

Your Answer

Accepted video resources