【发布时间】:2018-02-28 12:28:17
【问题描述】:
我正在实施“关注”CreateAPIView。
FollowCreateAPIView - 从 self.request.user 获取“登录用户” - 获取“登录用户”想要关注的“用户的 id”(来自 url) - 有了以上信息,关注创建新数据!
这里是 urls.py
url(r'^follow/(?P<user_id>\d+)$', FollowCreateAPIView.as_view(), name="user_profile"),
型号
class Follow(models.Model):
follower = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='follower')
following = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='following')
created_at = models.DateTimeField(auto_now_add=True)
CreateAPIView(我无法从 URL 获取 user_id;print(following_id) 返回 None
)
class FollowCreateAPIView(generics.CreateAPIView):
queryset = Follow.objects.all()
serializer_class = FollowCreateSerializer
def perform_create(self, serializer):
following_id = self.request.GET.get('user_id', None)
print(following_id) <<<<- HERE!
following_user = User.objects.filter(id=following_id)
serializer.save(follower=self.request.user, following=following_user)
序列化器
class FollowCreateSerializer(serializers.ModelSerializer):
class Meta:
model = Follow
fields = ()
- 你能解决这个问题吗?而这个
Like功能似乎很常见。 你有什么更好的方法吗?(如果你有……)
非常感谢!
【问题讨论】:
-
查看 DRF 的更新视图。我确信已经有代码可以满足您的需求 - 使用 URL 中的 ID 来获取模型实例或返回 404,以防找不到。您可以自定义子类中的剩余逻辑。
标签: django django-models django-forms django-rest-framework