I am creating a Blog post application and one of my requirements is that users can follow and unfollow one another.
I have created a profile model class
for each user and in that I have added the following
column to the user model
using a many to many field.
People Profile Model ->
class People(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
following = models.ManyToManyField(to=User, related_name='following', blank=True)
photo = models.ImageField(upload_to='profile_pics', blank=True,null=True)
Phone_number = models.CharField(max_length=255,null=True,blank=True)
Birth_Date = models.DateField(null=True,blank=True)
Created_date = models.DateTimeField(auto_now_add=True)
Updated_date = models.DateTimeField(auto_now=True)
Now I am listing all the posts on a webpage and for each post the author is also mentioned on the template. The requirement is that I need to give a button to follow or unfollow the post author. Now for the first time if the user comes on the page on if the author of the post is already followed that I need to show an unfollow button and for this I need to check every post author followings and make changes to my template as per the response from the DB.
This is the Query that I have written ->
posts = Post.objects.exclude(users=request.user)\
.select_related('user__people','ProductAvailability').prefetch_related('images_set','Likes')\
.annotate(comments_Count = Count('comments_post',distinct=True)).annotate(
Count('Likes',distinct=True),is_liked=Exists(
Post.Likes.through.objects.filter(
post_id=OuterRef('pk'), user_id=user_id
)
),isSaved=Exists(
Post.favourites.through.objects.filter(
post_id=OuterRef('pk'), user_id=user_id
)),
isFollowed=Exists(
People.following.through.objects.filter(
people_id=OuterRef('pk'), user_id=user_id
)
)
).all().order_by('-id')
Now the DB shows the record of user_id = 1
with people_id = 3
i.e user 1 follows people with id 3.
but the above query returns 0 as output in isFollowed.
Can someone point out the mistake I am making.
isFollowed=Exists( People.following.through.objects.filter(people_id=OuterRef('pk'), user_id=user_id)
Here thepeople_id = OuterRef('pk')
should be replaced withpeople_id = OuterRef(post.user.people.id)
But I dont know how I can make that happen as django does not allow this notation.