【问题标题】:How to render different data to the same page by two different views - Django如何通过两个不同的视图将不同的数据呈现到同一页面 - Django
【发布时间】:2018-05-18 23:01:43
【问题描述】:

我正在建立一个新闻网站。我需要显示 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 中获取数据。我猜这个问题是因为网址。

index.htmldetail.html的链接是

 <a href="{% url 'news:news_detail' news.pk %}">

news:news_detail是视图的url def newsDetailView

所以url直接指向def newsDetailView,和def hot_news无关。

我应该怎么做,才能将 def hot_news 中的数据渲染到与 def newsDetailView 相同的页面?

【问题讨论】:

  • 如果您想在单独的view 中处理 hot_news,Ajax 是一个很好的提示。 Ajax 将查询那个view,并在template 中刷新这部分
  • 是的,我认为类基视图可能是另一种方法,对吧?
  • 还有很多其他方法可以做到这一点,你所说的缓存背后的逻辑,一个view 可以用decorator,你只需要告诉django你想要哪个值作为cache 值及其持续时间。 FBV或CBV取决于你掌握得很好。
  • 嗨朋友我有一个新问题,你能帮忙吗?非常感谢! stackoverflow.com/questions/50431810/…

标签: python django django-views django-class-based-views


【解决方案1】:

所以你说得对,因为你要去的网址是'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,您可能还需要查看

【讨论】:

  • 真的很感激!这个答案太酷了,帮助我理解了如何很好地使用低级缓存api。
  • 嗨朋友我有一个新问题,你能帮忙吗?非常感谢! stackoverflow.com/questions/50431810/…
猜你喜欢
  • 1970-01-01
  • 2013-04-23
  • 2021-08-26
  • 1970-01-01
  • 2015-06-08
  • 2019-02-21
  • 2023-04-11
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多