Reputation: 4664
I'm using django 1.11.5
and python 3.5.
Using rest-framework
, I want to search a patient having uid
.
When I'm trying to have a serializer with only one field I get the error The
fieldsoption must be a list or tuple or "__all__". Got str.
.
Is there any solution to have only one field to search a user?
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
Upvotes: 5
Views: 7263
Reputation: 1814
You need to specify a tuple in the fields option:
fields = ('id', )
If you don't add the comma ,
python sees ('id')
as a string. That's why you see the Got str.
in the error message.
You can test it:
>>> type(('id'))
<type 'str'>
vs
>>> type(('id',))
<type 'tuple'>
Upvotes: 9
Reputation: 9397
You need to specify a tuple with one element, which requires a comma: ('uid',)
.
Upvotes: 2