python - Django Rest 框架中的最佳实现 follow 和 unfollow

标签 python django django-rest-framework

尝试在 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/

相关文章:

python - 让 os.path.join 与生成器一起工作?

django - 使用 Django Rest Framework 3.2.2 与现有对象的可写嵌套序列化器

Django SECURE_SSL_REDIRECT 中断使用内置客户端的单元测试

python - 如何防止 Django REST API CharFields 中的 XSS 攻击?

python - 检查列内的字符串错误行为 - Pandas

python - `ValueError: too many values to unpack (expected 4)` 与 `scipy.stats.linregress`

python matplotlib 使用按钮事件添加和删除文本到图形

python - 使用嵌套对象在 ModelViewSet 上发布 Django Rest Framework

python - TextMate 和 Django 集成 - 支持 {% %} 标记

python - 使用 Python 和 Angular(或 Django 或其他)的离线桌面 Web 应用程序