How to fetch users that i follow?

Viewed 35

I want to make a viewset to allow request.user (Authenticated user) to receive the users in a view that they follow. But i do not know how to make an appropriate queryset filter for it.

Models (Note: Author is the one following,profile is the one followed)

class User(AbstractUser,PermissionsMixin):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    email = models.CharField(max_length=255,unique=True)
    username =models.CharField(max_length=40,unique=True,default='undefinedusername')



class UserFollow(models.Model):

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    author = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following')
    profile = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers')

View

class FetchUserViewSet(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    queryset = User.objects.all()
    serializer_class = UserSerializer
    filter_backends = [FollowedUserFilterBackend]

Filter

class FollowedUserFilterBackend(filters.BaseFilterBackend):
    
    def filter_queryset(self, request, queryset, view):
        return queryset.filter(
            ???
        )     

I tried

following__author = request.user

but it returns the user that made the request,not the followed user. How can i do it?

1 Answers

You can filter with:

return queryset.filter(
    followers__author=request.user
)

Here we thus look for Users for which a UserFollow record exists where the profile (not the author) points to that user, and the author points to the logged in user.

Related