I want to realize in my Django blog «Top 5 trend post».
For this purpose, I implemented a Cron task that calls the function update_trends() once a day.
This function should reset hits counter in Redis db.
Hits counter is a Sorted Set with the structure: setname ("hits") score (hits amount) key (post id)
Here is the function:
import redis
from .models import Article
r = redis.Redis(host='localhost', port=6379, db=0)
def update_trends():
# deleting the counter with click statistics for the previous day
r.delete('hits')
# Assigning a zero value for each post id
articles_ids = Article.objects.values_list('pk', flat=True)
for article_id in articles_ids:
r.zadd('hits', 0, article_id)
When Cron fires, the sorted set "hits" is removed, but for some reason zero values for each post id are not written.
I can't understand why?
If I manually write in shell:
redis-cli zadd hits 0 1
Then the value is successfully set.
Also I have tried to use in update_trends() such way:
articles = Article.objects.all()
for article in articles:
r.zadd('hits', 0, article.pk)
But it doesn't work too.