0

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!

William
  • 3,724
  • 9
  • 43
  • 76

1 Answers1

4

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

Lemayzeur
  • 8,297
  • 3
  • 23
  • 50
  • So if I want to get the data of the week, can I use thetime = datetime.now() - timedelta(weeks=1) ? – William May 18 '18 at 19:53
  • Of course you can and also you could have done for `48 hours` `timedelta(days=2)` – Lemayzeur May 18 '18 at 19:56
  • Hi friend could you help me with this relative question?Thank you so much! https://stackoverflow.com/questions/50420252/how-to-render-different-data-to-the-same-page-by-two-different-views-django – William May 18 '18 at 23:02