社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

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

Vlad Ivanov • 4 年前 • 790 次点击  

我已经在模型中定义了方法,并尝试在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
 
790 次点击  
文章 [ 2 ]  |  最新文章 4 年前