I'm working on CS50w network on the followings/followers feature. I am stuck on counting the followers:
This is my model:
class Following(models.Model):
"""Tracks the following of a user"""
user = models.ForeignKey(User, on_delete=models.CASCADE)
followings = models.ManyToManyField(User, blank=True, related_name="followers")
Using the code below, I can successfully get the followings count:
user = Following.objects.get(user=user_instance)
followings = user.followings.count()
However, I can't get the followers, this is what I tried:
user = Following.objects.get(user=user_instance)
followers = user.followers.count()
It is worth mentioning that if I passed the user
and tried to get the `followers', I get it successfully using:
{{user.followers.count}}
However, I can't use this method since I need to handle corner cases in the backend.
I tried another method, however another problem arises. I tried to pass the user
to the HTMl. However if the user
lacks the followings
or followers
. I couldn't handle the situation correctly.
Here is my code to get a better idea:
try:
# Gets the profile
profile = Following.objects.get(user=user_instance)
except Following.DoesNotExist:
followings = 0 # I know these are wrong, but IDK what to do
followers = 0
I could use {{profile.followings.count}}
& {{profile.followers.count}}
to obtain them.
What if there isn't followers or followings in the first place?
local variable 'profile' referenced before assignment
The issue is that
Here it's not user object but Following model instance, that is why it's working.
user = Following.objects.get(user=user_instance)
followings = user.followings.count()
Here you writing user, but it's still Following model instance
# that is wrong
user = Following.objects.get(user=user_instance)
followers = user.followers.count()
You need to get user instance first with
user = User.objects.get(...)
followers = user.followers.count()
Or you can do like, but it doesn't make sense as you can get followers right from following instance, but just to show how would your approach work:
following_instance = Following.objects.get(user=user_instance)
user = following_instance.user
followers = user.followers.count()