Aggregate User Activity Over Time with Django Caching

  • Share this:

Code introduction


This function calculates the total user activity over a specified period. It uses Django's cache framework to store and retrieve data, and Django's ORM to fetch data from the database.


Technology Stack : Django, Django ORM, Django Cache Framework, Sum aggregation

Code Type : Django Model and Cache Aggregation

Code Difficulty : Intermediate


                
                    
import random
from django.core.cache import cache
from django.db.models import Sum
from django.utils.timezone import now

def aggregate_user_activity(arg1, arg2):
    """
    This function aggregates the total activity of users over a given period.
    It takes two arguments: start_date and end_date, both of which are strings in the format 'YYYY-MM-DD'.
    """
    start_date = arg1
    end_date = arg2
    # Retrieve user activity data from cache
    user_activity_data = cache.get(f"user_activity_{start_date}_{end_date}")
    if not user_activity_data:
        # If data is not in cache, fetch from database
        from .models import UserActivity
        user_activity_data = UserActivity.objects.filter(date__range=(start_date, end_date)).aggregate(Sum('activity'))
        # Cache the result for future requests
        cache.set(f"user_activity_{start_date}_{end_date}", user_activity_data, timeout=3600)
    return user_activity_data