Reputation: 89
So the thing is when the authenticated user(lets call it user1) follows a another user(lets call it user2). then user2 get added into user1's following list and user1 should get automatically added to user2's follower list.This i what I want to achieve. Can anyone help me with the logic?
class Follower(models.Model):
user = models.OneToOneField(UserModel,related_name="followers", verbose_name=_("User"), on_delete=models.CASCADE)
follower_user = models.ManyToManyField(UserModel, verbose_name=_("Follower"),related_name='follower_user')
class Following(models.Model):
user = models.OneToOneField(UserModel, related_name="following",unique=False, verbose_name=_("User"), on_delete=models.CASCADE)
following_user = models.ManyToManyField(UserModel, verbose_name=_("Following"), related_name='following_user')
class FollowerSerializer(ModelSerializer):
class Meta:
model = Follower
fields = ('user','follower_user')
read_only_fields = ()
class FollowingSerializer(ModelSerializer):
class Meta:
model = Following
fields = ('user','following_user')
read_only_fields = ()
class FollowerView(ListAPIView):
queryset = Follower.objects.all()
serializer_class = FollowerSerializer
permission_classes = [IsAuthenticated]
class FollowingView(ListCreateAPIView):
queryset = Following.objects.all()
serializer_class = FollowingSerializer
permission_classes = [IsAuthenticated]
Upvotes: 0
Views: 862
Reputation: 6296
You need to add a field to capture the follower id for creation in the FollowingSerializer since you will be creating only one following at a time.
class FollowingSerializer(ModelSerializer):
new_following = serializers.PrimaryKeyRelatedField(queryset=UserModel.objects.all(), required=True, write_only=True)
class Meta:
model = Following
fields = ('user', 'following_user', 'new_following')
read_only_fields = ('following_user')
def create(self, validated_data):
user = validated_data['user']
new_follwoing = validated_data['new_following']
user.following.following_user.add(new_follwoing)
new_follwoing.followers.following_user.add(user)
return user.following
Upvotes: 1