我正在建立一个新闻网站。我需要显示48小时最常查看的新闻,这部分位于detail.html页面。现在我正在使用这种方法。
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
News.objects.filter(id=news_pk).update(pv=F('pv') + 1)
time_period = datetime.now() - timedelta(hours=48)
host_news=news.objects.filter(date_created__gte=time_period).order_by('-pv')[:7]
return render(request, "news_detail.html", {
'news': news,
'host_news' : host_news
})
它工作得很好,但我的问题是,为了方便地使用缓存,我想将hot_news函数与 def newsDetailView 分开。
我试过了:
def hot_news(request):
time_period = datetime.now() - timedelta(hours=48)
hot_news =News.objects.filter(add_time__gt=time_period).order_by('-pv')[:7]
return render(request, "news_detail.html", {
'most_viewedh': most_viewedh
})
但是我无法在detail.html
中获取数据。我想这个问题是因为网址。
来自detail.html
的{{1}}的链接
index.html
<a href="{% url 'news:news_detail' news.pk %}">
是查看网址 def newsDetailView
因此,网址直接指向 def newsDetailView ,并且与 def hot_news 无关。
我该怎么办,以便将 def hot_news 中的数据渲染到与 def newsDetailView 相同的页面?
答案 0 :(得分:2)
所以你说的是正确的,因为你要去的网址是'news:news_detail'
,这是唯一被加载的视图。如果您确实想要从另一个视图加载数据,可以使用ajax加载hot_news数据并将其插入到页面中。
虽然如果你想要实现的只是缓存hot_news,这不是必需的。您可以使用django的低级缓存api,如下所示:
from django.core.cache import cache
def newsDetailView(request, news_pk):
news = get_object_or_404(News, id=news_pk)
News.objects.filter(id=news_pk).update(pv=F('pv') + 1)
# Get host_news from the cache
host_news = cache.get('host_news')
# If it was not in the cache, calculate it and set cache value
if not host_news:
time_period = datetime.now() - timedelta(hours=48)
host_news=news.objects.filter(date_created__gte=time_period).order_by('pv')[:7]
# Sets the cache key host_news with a timeout of 3600 seconds (1 hour)
cache.set('host_news', host_news, 3600)
return render(request, "news_detail.html", {
'news': news,
'host_news' : host_news
})
低级缓存api上的文档位于:https://docs.djangoproject.com/en/2.0/topics/cache/#the-low-level-cache-api
如果你还没有这样做,你可能还需要在settings.py中设置CACHES