尝试在 Django-rest 中实现关注者和关注者以及功能,如果我要不使用休息框架来创建它,我知道如何做到这一点。但这一次我几乎不知道如何做到这一点。
请:
1)假设我正在从事一个大项目,那么做这样的事情的最佳方法是什么?
2)我主要迷失在序列化器和 View 部分要做什么,我只知道在序列化器部分我单独选择以下模型
假设我有这样的个人资料模型
class Profile(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
following = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='followers', blank=True)
other content…….
请提供任何帮助,我们将不胜感激
最佳答案
将其添加到您的 urlpatterns
path('follow/<int:pk>/', FollowView.as_view({'post': 'follow'})),
path('unfollow/<int:pk>/', FollowView.as_view({'post': 'unfollow'})),
以及在您的休息 View 中
class FollowView(viewsets.ViewSet):
queryset = Profile.objects
def follow(self, request, pk):
# your follow code
return Response({'message': 'now you are following'}, status=status.HTTP_200_OK)
def unfollow(self, request, pk):
# your unfollow code
return Response({'message': 'you are no longer following him'}, status=status.HTTP_200_OK)
要将项目添加到 ManyToManyField,您必须使用 add 函数。在本例中,它将使用 Profile 的实例。
profile.following.add(follow_profile) # To add a following
profile.following.remove(follow_profile) # To remove a following
也就是说你的函数看起来像这样。
def follow(self, request, pk):
own_profile = request.user.profile_set.first() # or your queryset to get
following_profile = Profile.objects.get(id=pk)
own_profile.following.add(following_profile) # and .remove() for unfollow
return Response({'message': 'now you are following'}, status=status.HTTP_200_OK)
关于python - Django Rest 框架中的最佳实现 follow 和 unfollow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58934300/