Django Wagtail:使用自己的 object.method 而不是重写 object.get_context 方法访问数据是不好的做法吗?

Django Wagtail: Is it bad practise access data using own object.method instead of rewriting object.get_context method?

我正在玩 Django Wagtail。关于在模板中呈现数据,我知道官方方法是在我的页面对象中重写 get_context 方法。但我可以只写我自己的方法,我发现它对我来说更好更清晰。只是想问问这是否可行,或者是否有任何问题、问题、性能问题? 非常感谢。

标准方式:

class Blog(Page): 
    template = "blog/blog.html"        

    def get_context(self, request):
        context = super().get_context(request)
        get_posts = self.get_children().live().order_by('-first_published_at').all()
        context['list_all'] = get_posts
        return context

使用自己的方法:

class Blog(Page): 
    template = "blog/blog.html"        

    def list_all(self):
       get_posts = self.get_children().live().order_by('-first_published_at').all()
       return (get_posts)

在模板中呈现 - 标准方式:

  {% for post in list_all %}
      {{post.title}}
  {% endfor %}

在模板中呈现 - 自己的方法:

  {% for post in self.list_all %}
      {{post.title}}        
  {% endfor %}

两种方法都可以。使用方法的唯一真正缺点是您无法轻松访问请求对象,因此(例如)您将无法实现基于 URL 参数分页或过滤的列表方式。

将您的业务逻辑放在方法中也意味着您可以在模板渲染之外的其他地方使用它,例如 outputting it over the API or using it in search indexing