django / rest:我可以只有一个字段的序列化器吗?

时间:2017-10-22 12:19:22

标签: python django django-rest-framework

我正在使用django 1.11.5和python 3.5。

使用rest-framework,我想搜索有uid的患者。

当我尝试使用只有一个字段的序列化程序时,我收到错误The字段option must be a list or tuple or "__all__". Got str.

是否只有一个字段可以搜索用户?

serializers.py

class GetUserSerializer(serializers.ModelSerializer):
    id = serializers.CharField(source='uid')

    class Meta:
        model = User
        fields = ('id')

views.py

class GetUser(CreateAPIView):
    permission_classes = ()
    serializer_class = GetUserSerializer

    def get(self, request):
        serializer = GetUserSerializer(data=request.data)
        # Check format and unique constraint
        if not serializer.is_valid():
            return Response(serializer.errors, \
                            status=status.HTTP_400_BAD_REQUEST)
        data = serializer.data


        if User.objects.filter(uid = data['id']).exists():
            user = User.objects.get(uid = data['id'])
            resp = {"user":{"uid":user.uid, "firstname":user.firstname, "yearofbirth": user.yearofbirth, \
                            "lastnames": user.lastname, "othernames": user.othernames}}
            return Response(resp, status=status.HTTP_200_OK)

        else:

            resp = {"error": "User not found"}
            return Response(resp, status=status.HTTP_404_NOT_FOUND)

models.py

class User(models.Model):
    uid = models.CharField(max_length=255, unique=True,default="0")
    firstname = models.CharField(max_length=255)
    lastname = models.CharField(max_length=255, blank=True)
    othernames = models.CharField(max_length=255, blank=True)
    yearofbirth = models.SmallIntegerField(validators=[MinValueValidator(1900),
                                           MaxValueValidator(2018)], null = False

2 个答案:

答案 0 :(得分:5)

您需要在字段选项中指定元组:

fields = ('id', )

如果不添加逗号, python,请将('id')视为字符串。这就是您在错误消息中看到Got str.的原因。

你可以测试一下:

>>> type(('id'))
<type 'str'>

VS

>>> type(('id',))
<type 'tuple'>

答案 1 :(得分:2)

您需要指定一个包含一个元素的元组,这需要逗号:('uid',)