本文介绍了如何避免在Django中重复相同的代码块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的4个函数中有相同的代码块,有什么办法可以避免重复相同的代码块?
I have the same code block in 4 of my functions,is any way that can avoid repeating the same code block?
这里是相同的代码块:
def function_name():
...some code...
hot_news_48h = h_mostViewed(48, News, '-pv')
hot_news_1w = w_mostViewed(1, News, '-pv')
...some code...
return render(request, "template_name.html", {
...some code...
'hot_news_48h': hot_news_48h,
'hot_news_1w': hot_news_1w,
...some code...
})
这里是function1:
Here is function1:
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
tags = news.tag.annotate(news_count=Count('news'))
News.objects.filter(id=news_pk).update(pv=F('pv') + 1)
hot_news_48h = h_mostViewed(48, News, '-pv')
hot_news_1w = w_mostViewed(1, News, '-pv')
relative_news = News.objects.filter(tag__id__in=news.tag.all()).exclude(id=news_pk)[:6]
return render(request, "news_detail.html", {
'news': news,
'tags': tags,
'hot_news_48h': hot_news_48h,
'hot_news_1w': hot_news_1w,
'relative_news': relative_news
})
这里是function2:
Here is function2:
def tagNewsList(request, tag_pk):
tag = get_object_or_404(Tag, pk=tag_pk)
news_list = News.objects.filter(tag=tag)
hot_news_48h = h_mostViewed(48, News, '-pv')
hot_news_1w = w_mostViewed(1, News, '-pv')
return render(request, "tags_list.html", {
'news_list': news_list,
'tag': tag,
'hot_news_48h': hot_news_48h,
'hot_news_1w': hot_news_1w,
})
有没有朋友知道如何避免呢?
Any friend know how to avoid it?Thank you so much!
推荐答案
非常感谢@ Lemayzeur!
Thanks @ Lemayzeur so much!
我终于通过使用{%include news_rank.html%} + context_processors解决了这个问题。它为我节省了很多代码。
I finally solved the issue by using {% include news_rank.html %} + context_processors.It saves me a lot of code.
我今天学习了如何创建自定义上下文处理器。
I learned how to Create custom context processor today.
这篇关于如何避免在Django中重复相同的代码块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!