[Answered ]-Keep track of follow/unfollow events django

1👍

create two queries:

people_who_unfollowed = FollowHistory.objects.filter(timestamp__year=2022, timestamp__month=03, timestamp__day=12,page=page, followed=False)
people_who_followed   = FollowHistory.objects.filter(timestamp__year=2022, timestamp__month=03, timestamp__day=12,page=page, followed=True)

now your output for 12 march 2022 will be:

followings = len(people_who_followed) - len(people_who_unfollowed)

or there is another approach:

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.DateField(auto_now_add=True)
   counter = models.IntegerField()

when any user wants to follow or unfollow:

today = date.today()
get_or_create_Follow_history_object, created = FollowHistory.objects.get_or_create(timestamp__year=today.year, timestamp__month=today.monnh, timestamp__day=today.day,page=page)
if created == True:
    # here is some logic with created FollowHistory object
    # you need to up or down counter of this model
    # get_or_create_Follow_history_object.counter = get_or_create_Follow_history_object.counter + 1 #(or-1 if unfollow)
    # get_or_create_Follow_history_object.save()
else:
    # this is for object which already exists
    # get_or_create_Follow_history_object.counter = get_or_create_Follow_history_object.counter + 1 #(or-1 if unfollow)
    # get_or_create_Follow_history_object.save()
   

this will get FollowHistory if it is exists and created variable will be False,

if it doesnt exist, it will be created, and created variable will be True

at the end of the day you will have many FollowHistory objects wich will correspond on how many follows/unfollows happend (.counter property) and its date, so you can make a query:

all_follow_history_objects = FollowHistory.objects.filter(page=page, user=user)

and send it to your html page, where you can output all data in table in for loop

{% for i in all_follow_history_objects %}
    <p>date: {{i.timestamp}} ---  counter: {{i.counter}}</p>
{% endfor %}

Leave a comment