[英]Django Wagtail: Is it bad practise access data using own object.method instead of rewriting object.get_context method?
I am playing with Django Wagtail . 我正在玩Django Wagtail 。 Concerning rendering data in templates, I know that official way is rewrite get_context method in my page object.
关于在模板中呈现数据,我知道官方方法是在页面对象中重写get_context方法。 But I can just write my own method, I find it better and more clear for me.
但是我可以编写自己的方法,我发现它对我来说越来越好。 Just want to ask if this is possible way how to do that or is there any problem, catch, performance issues?
只是想问问这是否是可能的方法,还是有任何问题,捕获,性能问题? Thank you very much.
非常感谢你。
standard way: 标准方式:
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
using own method: 使用自己的方法:
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)
Render in template - standard way: 模板渲染-标准方式:
{% for post in list_all %}
{{post.title}}
{% endfor %}
Render in template - own method: 在模板中渲染-自己的方法:
{% for post in self.list_all %}
{{post.title}}
{% endfor %}
Both approaches are fine. 两种方法都很好。 The only real disadvantage of using a method is that you don't have easy access to the request object, so (for example) you won't be able to implement a listing that's paginated or filtered based on URL parameters that way.
使用方法的唯一真正的缺点是您无法轻松访问请求对象,因此(例如)您将无法实现以这种方式基于URL参数进行分页或过滤的列表。
Putting your business logic in methods also means that you can potentially use it in other places besides template rendering, such as outputting it over the API or using it in search indexing . 将您的业务逻辑放入方法中还意味着,除了模板呈现之外,您还可以在其他地方使用它,例如通过API输出它或在搜索索引中使用它 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.