I am failing to build logic regarding streak feature similar to Snapchat. Here is how streak gets counted in snapchat problem is. if the user adds a new data record once every 24 hours streak is one irrespective of how many records he/she adds and streak is 0 if he/she fails to add with in next time period and adds by +1 in next 24 hours timeframe from last record added.
Streak is actually based on user and answer if user adds answer than streak is maintained.
I tried this code in django but any help in any language will be valuable
class ModelAnswer(BaseModel):
questions = models.ForeignKey(
to=Questions,
on_delete=models.CASCADE
)
answer = models.TextField()
user = models.ForeignKey(User, on_delete=models.CASCADE)
current_streak = models.PositiveIntegerField(
null=True,
blank=True,
default=0,
editable=False
)
here is my main logic part this is not working as per required
def save(self, *args, **kwargs):
today = timezone.now()
yesterday = today - timedelta(days=1)
print(today,yesterday)
# get the categories created yesterday to maintain the streak
answers_created_yesterday = ModelAnswer.objects.filter(
Q(created_at__gte=yesterday),
Q(created_at__lt=today),
user=self.user
).order_by('-id').last()
if answers_created_yesterday is not None:
self.current_streak = answers_created_yesterday.current_streak + 1
else:
self.current_streak = 1
print(self.current_streak)
super(ModelAnswer, self).save(args, kwargs)
from How do I implement snap chat streak like feature?
No comments:
Post a Comment