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
It is not necessary to use a serializer. You can do what you would like to achieve in a view. However, serializers help you a lot. If you don't want to use serializer, you can inherit APIView at a function-based-view.
The ModelSerializer class is the same as a regular Serializer class, except that: It will automatically generate a set of fields for you, based on the model. It will automatically generate validators for the serializer, such as unique_together validators.
You could create a View that extends APIView and return directly the response on get method without Serializer. There are ModelSerializer, ViewSet which are more related to Models, but everything is not implemented on them, they extend other classes, so you could go to the parent class and extend it.
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'>
You need to specify a tuple with one element, which requires a comma: ('uid',)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With