我正在使用
django 1.11.5和
python 3.5.
使用rest-framework,我想搜索有uid的病人.
当我尝试只有一个字段的序列化程序时,我得到错误Thefieldsoption必须是列表或元组或“__all__”.得了..
是否有任何解决方案只有一个字段来搜索用户?
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
最佳答案 您需要在fields选项中指定一个元组:
fields = ('id', )
如果你不添加逗号,python将(‘id’)视为一个字符串.这就是你看到Got str的原因.在错误消息中.
你可以测试一下:
>>> type(('id'))
<type 'str'>
VS
>>> type(('id',))
<type 'tuple'>