I am building a sort of social media app, where users can follow certain pages. I want the page managers to be able to visualize their followers in a chart for each day/week or so. So I am thinking about how to implement the following system. For now, I have this model:
class FollowHistory(models.Model):
user = models.ForeignKey('User', on_delete=models.CASCADE, related_name="follow_history")
page = models.ForeignKey('Page', on_delete=models.CASCADE, related_name="follower_history")
timestamp = models.DateTimeField(auto_now_add=True)
followed = models.BooleanField()
When a user clicks Follow, I create an instance with followed = True, and the timestamp of the event. When a user clicks Unfollow, I do the same, but with followed = False.
I am struggling to figure out how to query the data in a way for a page to see how many followers they had each day. So far I have tried this:
FollowHistory.objects.filter(page=page, followed=True)\
.annotate(ts_day=Trunc('timestamp', 'day'))\
.values('ts_day')\
.annotate(followers=Count('id'))
But that just gives me the count of events that happened in a day, so if I follow and unfollow a company 10 times, then it will count 10 times. I only need to know by the end of the day, did I follow or not?
Maybe there is a better implementation of the model that you could recommend, I am open to that too. Thanks!
Update:
I managed to set up a query that outputs the change in number of followers each day:
FollowHistory.objects.filter(page=page)\
.values('timestamp')\
.annotate(followings=(Count(Case(When(followed=True, then=1)))-Count(Case(When(followed=False, then=1)))))\
.order_by('timestamp')
Where followings calculates the difference between follows and unfollows for each day.
The result is something like this:
| date | followings |
|---|---|
| 28.02.2022 | 1 |
| 01.03.2022 | 3 |
| 04.03.2022 | -1 |
| 05.03.2022 | 2 |
| 08.03.2022 | 0 |
So there are still a few problems with this:
- I need the cumulative sum, so a column that goes 1, 4, 3, 5, 5
- How would I fill in the missing dates when no one follows or unfollows?
- On the 8th of march, followings equals 0 because someone followed and later unfollowed a page.
I don't know if I should stick with this approach or just find another way to set up the FollowHistory model?