My blog development (014)

Time:2020-9-10

Add a title to the previous Icon: home.html Add the x-axis category to the title in

Title: {text: 'reading change in the last 7 days'},

My blog development (014)
Add a get in utils_ today)hot_ The data method is used to get the hot data of today’s day

# utils.py
......
def get_today_hot_data(content_type):
    """
    Used to get hot data within 24 hours today
    """
    today = timezone.now().data()
    #The following sentence: used to read the reading table from the database model, and then sort it in reverse order (more then less) and return (character set)
    read_details = ReadDetail.objects.filter(content_type=content_type,date=today).order_by('-read_num')
    return read_ Details [: 7] ා used to access the previous blog post

The view function introduces the method defined above, and then uses this method in home to get today’s hot data, and then puts it in context,

# mysite\views.py
from read_statistics.utils import get_seven_days_read_data,get_today_hot_data

...
def home(request):
    ...
    today_hot_data = get_today_hot_data(blog_content_type)
    ...
    context['today_hot_data'] = today_hot_data
    ...

write in home.html in

{# home.html#}
    <div class="hot-data">
        <h3>Popular blogs today</h3>
        <ul>
            {% for hot_data in today_hot_data %}
                <li><a href="{% url 'blog_detail' hot_data.content_object.pk %}">{{ hot_data.content_object.title }}</a>({{ hot_data.read_num }})</li>            
            {% empty %}
                <li>There are no popular blogs today</li>
            {% endfor %}
        </ul>
    </div>

Operation display
My blog development (014)
There is no blog post. Let’s create a blog post
My blog development (014)
Add yesterday’s top blog posts:
utils.py Add get in_ yestday_ hot_ data

......
def get_yesterday_hot_data(content_type):
    """
    Used to get yesterday's hot blogs
    """
    today = timezone.now().date()
    yesterday = today -  datetime.timedelta Yesterday is equal to today minus 1 day; timedelta (days = x) means the difference is x days
    read_details = ReadDetail.objects.filter(content_type=content_type, date=yesterday).order_by('-read_num')
    return read_details[:7]

Back to views.py And call
Import and call

# mysite/views.py
from read_statistics.utils import get_seven_days_read_data,get_today_hot_data,get_yesterday_hot_data
......
def home(request):
    ...
    context['yesterday_hot_data'] = get_yesterday_hot_data(blog_content_type)
    ...

home.html Add yesterday’s hot click code

<div class="hot-data">
        <h3>Yesterday's hot blog</h3>
        <ul>
            {% for hot_data in yesterday_hot_data %}
                <li><a href="{% url 'blog_detail' hot_data.content_object.pk %}">{{ hot_data.content_object.title }}</a>({{ hot_data.read_num }})</li>            
            {% empty %}
                <li>There were no popular blogs yesterday</li>
            {% endfor %}
        </ul>
    </div>

The results are as follows:
My blog development (014)

Among them, if there are more than one blog post yesterday, the lower left corner will also display more than one, which is very difficult to see. So I hope to display only the first seven articles. The method is as follows: read_ details[:7]

Get and display the hot of the last seven days_ data:
stay views.py New get in_ 7_ days_ hot_ The blogs() function (import timezone) is used to associate the model,

from django.utils import timezone
from django.db.models import Sum
......

def get_7_days_hot_blogs():
    today = timezone.now().date()
    date = today - datetime.timedelta(days=7)
        #Filter: filter; values: extract the specified data; annotate: grouping statistics; order_ By: sort in reverse order;
    blogs = Blog.objects \
                .filter(read_details__date__lt=today, read_details__date__gte=date) \
                .values('id', 'title') \
                .annotate(read_num_sum=Sum('read_details__read_num')) \
                .order_by('-read_num_sum')
    return blogs[:7]

Because the statistics are scattered, we use the values and annotate methods to group the blog articles

Because of the usage problem on Django, the operation here is as follows:

models.py Import genericrelation and readdetails in, and add read to blog_ Deatils for association model

# models.py
from django.contrib.contenttypes.fields import GenericRelation
from read_statistics.models import ReadNumExpandMethod, ReadDetail

class Blog(models.Model,ReadNumExpandMethod):
    ......
    read_details = GenericRelation(ReadDetail)
    ......

write in home.html Chinese:

<div class="hot-data">
        <h3>7 days of hot blogs</h3>
        <ul>
            {% for hot_blog in hot_blogs_for_7_days %}
                <li><a href="{% url 'blog_detail' hot_blog.id %}">{{ hot_blog.title }}</a>({{ hot_blog.read_num_sum }})</li>            
            {% empty %}
                <li>There were no popular blogs yesterday</li>
            {% endfor %}
        </ul>
    </div>

My blog development (014)

other:
Each run time has to calculate several pieces of data, which is time-consuming;

  • Memory cache
  • Database cache
  • File cache

Here I use the database cache:
Find the database cache from the cache search results on Django’s official website, copy the code, and copy it in settings.py Medium,

#Cache settings
CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
        'LOCATION': 'my_cache_table',
    }
}

Then create the cache table: Python manage.py createcachetable

stay views.py Reference and use in
Import caches and get the cache data of popular blogs for 7 days. Note that the s in cache should be removed

from django.core.cache import cache
......
def home(request):
    ...
     #Get cache data of 7-day popular blogs
    hot_blogs_for_7_days = cache.get('hot_blogs_for_7_days')
    if hot_blogs_for_7_days is None:
        hot_blogs_for_7_days = get_7_days_hot_blogs()
        cache.set ('hot_ blogs_ for_ 7_ days', hot_ blogs_ for_ 7_ The failure time is 3600 seconds (one hour)
    ...
    context['hot_blogs_for_7_days'] = hot_blogs_for_7_days
    ......

Perfect CSS code, beautiful display

div.hot-data {
    text-align: center;
    margin-top: 2em;
}

The results are as follows:
My blog development (014)