我已经在模型中定义了方法,并尝试在django模板中使用它,该模板使用
ListView
class Book(models.Model):
name = models.CharField(max_length=32)
price = models.IntegerField()
created_at = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE)
def get_total_sum(self):
return super().objects.all().filter(user=self.user).aggregate(models.Sum('price'))
我的观点:
from django.views.generic.list import ListView
from book.models import Book
class BookView(ListView):
template_name = 'book.html'
# I'm using this to order book by created date
def get_queryset(self):
return Book.objects.filter(user=self.request.user).order_by('-created_at')
我的模板:
Total books: {{ object_list|length }}
Total price of all books: # I've no idea how to display them here, when using class based view