Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在基于类的视图的django模板中使用模型方法_Python_Django - Fatal编程技术网

Python 如何在基于类的视图的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(

我在我的模型中定义了方法,并试图在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

您可以做的一件事是使用定制的
模板标签

遵循以下步骤:

  • 在应用程序目录中创建文件夹
    templatetags
  • 在例如
    book\u filter.py
    \uuuu init\uuuu.py
  • 内部
    book_filter.py
    在过滤器下方复制
  • book_filter.py 现在,在html文件中,执行以下操作:

    {% 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 }}
    
    另一种方法是通过在view
    get\u context
    方法中使用Python代码获取所需的值并将其注入到上下文中,从而注入所需的值。对于每个Book实例的计算值不同的情况,这显然不起作用,而属性是理想的。当代码不是作为属性自然绑定到一个类时,自定义模板标记是理想的

    {{ book.get_total_sum }}