问题
I have the same code block in 4 of my functions,is any way that can avoid repeating the same code block?
Here is 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...
})
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
})
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!
回答1:
Thanks @ Lemayzeur so much!
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.
来源:https://stackoverflow.com/questions/51903751/how-to-avoid-repeating-same-code-block-in-django