Python 如何在基于类的视图的django模板中使用模型方法
我在我的模型中定义了方法,并试图在django模板中使用它,该模板使用Python 如何在基于类的视图的django模板中使用模型方法,python,django,Python,Django,我在我的模型中定义了方法,并试图在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(
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
您可以做的一件事是使用定制的
模板标签
:
遵循以下步骤:
templatetags
book\u filter.py
和\uuuu init\uuuu.py
book_filter.py
在过滤器下方复制{% load book_filter %}
Total price of all books: {{object_list|total_price}}
请使用此链接作为参考:
希望这对您有所帮助。如果您想使用
Book.get\u total\u sum
在模板中,您需要将其设置为属性
@property
def get_total_sum(self):
return super().objects.all().filter(user=self.user).aggregate(models.Sum('price'))
在模板中
{{ book.get_total_sum }}
另一种方法是通过在viewget\u context
方法中使用Python代码获取所需的值并将其注入到上下文中,从而注入所需的值。对于每个Book实例的计算值不同的情况,这显然不起作用,而属性是理想的。当代码不是作为属性自然绑定到一个类时,自定义模板标记是理想的
{{ book.get_total_sum }}