[Answer]-How to display data from django class methods in templates ?

1👍

When you do something like:

{{ object_list.totalAssets }}

You are calling a instance method of a QuerySet.
I don’t know why you dont want to use {{ object_list.count }}, but you can add the count to the template context:

class AssetList(ListView):
    model = Assets

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(AssetList, self).get_context_data(**kwargs)
        context['total_assets'] = self.model.objects.all().count()
        return context

and then in your template:

{{ total_assets }}

EDIT

class Assets(models.Model):
    id = models.AutoField(primary_key=True)
    serial = models.CharField(unique=True, max_length=100)

    def __str__(self):
       return self.serial

    @classmethod
    def total_assets(cls):
        return cls.objects.all().count()

class AssetList(ListView):
    model = Assets

    def get_context_data(self, **kwargs):
        # Call the base implementation first to get a context
        context = super(AssetList, self).get_context_data(**kwargs)
        context['total_assets'] = self.model.total_assets()
        return context

0👍

You might be able to use the @property decorator to achieve this, although I’ve never tried it with a class method. To be honest, you might want a custom manager for this, the logic in the code above seems a bit wrong.

class Assets(models.Model):

    @property
    def totalAssets(self):
        return "blah"

0👍

Maybe that: totalAssets needs to be called by an object and not by a list ?

👤Magda

Leave a comment