Py学习  »  Django

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

Nikix • 4 年前 • 444 次点击  

我在玩 Django摇尾巴 . 关于在模板中呈现数据,我知道官方的方法是在我的页面对象中重写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 %}
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/50601
 
444 次点击  
文章 [ 1 ]  |  最新文章 4 年前
gasman
Reply   •   1 楼
gasman    4 年前

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

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