Py学习  »  Django

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

Vlad Ivanov • 4 年前 • 784 次点击  

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

如果你想用 Book.get_total_sum

  @property
  def get_total_sum(self):
      return super().objects.all().filter(user=self.user).aggregate(models.Sum('price'))

在模板中

{{ book.get_total_sum }}

另一种方法是通过在视图中使用Python代码获取所需的值来注入 get_context 方法并将其注入上下文中。对于每个Book实例不同的计算值,这显然不起作用,并且属性是理想的。当代码不是作为属性自然绑定到一个类时,自定义模板标记是理想的选择

Sam
Reply   •   2 楼
Sam    4 年前

你可以做的一件事是使用自定义 templatetags :

遵循以下步骤:

  1. 模板标记 在你的应用程序目录中
  2. book_filter.py __init__.py
  3. 里面 书本过滤器.py

书本过滤器.py

from django import template
egister = template.Library()

@register.filter
def total_price(amounts):
    total = 0
    for amount in amounts:
        total += amount.price
    return total

现在在html文件中,执行以下操作:

{% load book_filter %}

Total price of all books: {{object_list|total_price}}

使用此链接作为参考: custom-template-tags