Reputation: 203
I am trying work out how filter who follows the logged in user/who is followed by the logged in user using Django Rest Framework. However, all I seem to be returning is ALL users who have been followed by any user or are following any user, it is not specific to the logged in user (the front end view (numbers are the user PK), the API view).
I make a GET Request with the pk of the logged in user via an AJAX call but can't seem to filter specifically against that. I'd be grateful for any help!
Here is my model:
class UserConnections(models.Model):
follower = models.ForeignKey(User, related_name="following", on_delete=models.CASCADE)
followed = models.ForeignKey(User, related_name="followers", on_delete=models.CASCADE)
Here are the relevant serializers:
class UserConnectionListSerializer(serializers.ModelSerializer):
class Meta:
model = UserConnections
fields = ['follower','followed']
class UserConnectionSerializer(serializers.ModelSerializer):
class Meta:
model = UserConnections
fields = '__all__'
depth = 2
Here is the views.py
# gets list of who logged in user is following
class FollowingViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserConnectionListSerializer
queryset = UserConnections.objects.all()
def get_serializer_class(self):
if self.request.method == 'GET':
return serializers.UserConnectionSerializer
return self.serializer_class
def get_followers(request):
if request.method == "GET":
user_id = self.request.GET.get('current_user_id', None)
return UserConnections.objects.filter(follower__id=user_id)
# gets list of followers who follow logged-in user
class FollowerViewSet(viewsets.ModelViewSet):
serializer_class = serializers.UserConnectionListSerializer
queryset = UserConnections.objects.all()
def get_serializer_class(self):
if self.request.method == 'GET':
return serializers.UserConnectionSerializer
return self.serializer_class
def get_followers(request):
if request.method == "GET":
user_id = self.request.GET.get('current_user_id', None)
return UserConnections.objects.filter(followed__id=user_id)
Upvotes: 0
Views: 266
Reputation: 1520
You need to override get_queryset
:
class FollowingViewSet(viewsets.ModelViewSet):
...
# The indentation is in `class` level
def get_queryset(self):
user_id = self.request.GET.get('current_user_id', None)
return UserConnections.objects.filter(follower__id=user_id)
and for FollowerViewSet
:
class FollowerViewSet(viewsets.ModelViewSet):
...
def get_queryset(self):
user_id = self.request.GET.get('current_user_id', None)
return UserConnections.objects.filter(followed__id=user_id)
Upvotes: 1