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"
- [Answer]-Django app cannot be accesed remotely with Apache+mod_wsgi
- [Answer]-Using django variables in Javascript
- [Answer]-Why is my middleware not setting request attributes on logout?
- [Answer]-Django + MySQL, form/create mysql query to pass a valid argument to the url
- [Answer]-Server-side resource file loading
- [Answer]-Django DateTimeField User Input
- [Answer]-Is there a way to see the salt state converted to the actual command that is being run?
- [Answer]-Django base64 field filtering
- [Answer]-Export many-to-many relations of object in admin with Django Import-Export
Source:stackexchange.com