Home > Software engineering >  Django Consecutive Days and Max Consecutive days Query
Django Consecutive Days and Max Consecutive days Query

Time:07-19

I have a following model.

class CategoryModel(BaseModel):
    name = models.CharField(max_length=100)
    icon = models.ImageField(upload_to=upload_icon_image_to)
    description = models.CharField(max_length=100)
    user = models.ForeignKey(User,on_delete=models.CasCade)

    def __str__(self):
        return self.name

The basic idea is that whenever a user added a category In one day whether being 1 or 20 records it is regarded as 1 streak and if the user again adds a new category then it is regarded as a 1 streak so current streak will be 2 and max streak is also 2 if user consecutively adds for 5 days streak is 5 days as it is max streak.

I just want to display as

{
"current_streak":3,
"max_streak":12
}

here current streak is 3 but previous streak set was 12 so it regarded as max streak Any Idea how I can achieve this query?

CodePudding user response:

I would suggest a few things:

  1. Overriding the .save() method or adding a post_save signal to CategoryModel so that you can process the streak logic.
  2. Track when categories are created, this should be a simple created_on DateTime field.
  3. Track the current_streak and max_streak on the User model

As for the implementation of tracking the streaks, something like this should work:

from datetime import datetime, timedelta

class User
   ...

   def update_streak(self):
      """ 
      When a category is created, check whether a category was created 
      yesterday or not. If it was then add  1 to the streak, otherwise set 
      the streak to 1. Then check if the max streak has been bested.
      """
      today = datetime.now().date()
      yesterday = today - timedelta(days=1)

      # get the categories created yesterday to maintain the streak
      categories_created_yesterday = self.categorymodel_set.filter(
        created_on__gte=yesterday,
        created_on__lt=today
      )
   
      if categories_created_yesterday.exists():
          self.current_streak  = 1
      else:
           self.current_streak = 1

      if self.current_streak > self.max_streak:
         self.max_streak = self.current_streak      

      self.save()

When a category has been created, you can call category.user.update_streak()

  • Related