Py学习  »  Django

如何在基于类视图的django模板中使用模型方法

Vlad Ivanov • 5 年前 • 1553 次点击  

我已经在模型中定义了方法,并尝试在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
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/56511
 
1553 次点击  
文章 [ 2 ]  |  最新文章 5 年前