How to get data from last 48 hours - Django

╄→гoц情女王★ 提交于 2019-12-25 01:49:33

问题


I'm building a news website.I need display 48 hours most viewed news. So I need first to get the 48 hours news, and then get its pv. Currently I'm using a very complicated method which is from a tutorial:

def get_two_days_read_data(content_type):
    today = timezone.now().date()
    dates = []
    read_nums = []

    for i in range(2, 0, -1):
        date = today - datetime.timedelta(days=i)
        dates.append(date.strftime('%m/%d'))
        read_details = ReadDetail.objects.filter(content_type=content_type, date=date)
        result = read_details.aggregate(read_num_sum=Sum('read_num'))
        read_nums.append(result['read_num_sum'] or 0)
    return dates, read_nums

My question is, is there any easier way?

For example something like this:

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)
    48_hours_hot_news = news.objects.filter(**48_housrs**).order_by('-pv')

    return render(request, "news_detail.html", {
        'news': news,
        '48_hours_hot_news' : 48_hours_hot_news
    })

Any friends can help?Thank you so much!


回答1:


You can do it with filter, your substract 48 hours from his date created, in case its result is greater than 48 hours or equal, you got recent news

from datetime import datetime, timedelta

thetime = datetime.now() - timedelta(hours=48)
results = news.objects.filter(date_created__gte=thetime)

Note a variable name can't be started with digit : 48_hours_hot_news : WRONG



来源:https://stackoverflow.com/questions/50418200/how-to-get-data-from-last-48-hours-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!