我正在实施'关注' CreateAPIView。
FollowCreateAPIView - 登录用户'来自self.request.user - 获取用户 ID '谁登录用户'想跟随(来自网址) - 根据上述信息,请关注创建新数据!
这是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(我无法通过网址获取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
功能似乎很常见。 你有更好的方法吗?(如果你有...)非常感谢你!
答案 0 :(得分:3)
我认为你可以用kwargs获得价值。此外,您可以使用get代替过滤器,因为id
是增量且唯一的。
try:
following_user = User.objects.get(id=self.kwargs['user_id'])
except User.DoesNotExist:
raise Http404
感谢Risadinha指出这一点。