DJANGO,DRF:请求ID返回NONE值,而不是用户对象

时间:2018-08-26 03:14:41

标签: django django-models django-rest-framework django-views

我想使用DRF在Django中创建关注者选项,所以在这里我的models.py

class Connect(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, unique = True, related_name = 'rel_from_set',on_delete=models.CASCADE)
    following = models.ManyToManyField(settings.AUTH_USER_MODEL,  related_name = 'follwed_by')
    def __str__(self):
        return str(self.following.all().count())

urls.py

url(r'^conn/(?P<id>\d+)', ConnectApi),

serializer.py

class ConnectSerializer(serializers.ModelSerializer):
    class Meta:
        model=Connect
        fields=('user','following')

views.py

@api_view(['GET','POST'])
def ConnectApi(request,id):
    user_id=request.POST.get('id')
    print(user_id)
    # user_id=request.GET['id']
    # action=request.POST.get('action')
    if user_id :
    # if user_id and action:

        try:
            user1=User.objects.get(id=user_id)
            if user1 :
                Connect.objects.get_or_create(user=request.user,
                                                following=user1)
            else:
                Connect.objects.filter(user=request.user,
                                        following=user).delete()
            return JsonResponse({'status':'ok'})
        except:
            return JsonResponse({'status':'ki'})
    return JsonResponse({'status':'ko'})

但是每当我启动网址

http://127.0.0.1:8000/connect/conn/2

这是回应

{"status": "ko"}

,在终端中,我可以看到“ NONE”  用于print(user_id)命令

我不知道我在哪里犯了错误,我不认为这是使追随者发挥作用的最佳实践,如果您知道的话,请告诉我

1 个答案:

答案 0 :(得分:1)

您正在通过网址传递 id ,并且在 视图功能 中直接使用 。因此,您不想从其他地方查询它

所以,使用它,


@api_view(['GET', 'POST'])
def ConnectApi(request, id):
    user_id = id
    print(user_id)
    # your code