需要进行简单的检查:如果用户存在则返回True,否则返回False。我正在尝试使用自定义json答案解决此问题,不确定它是否正确处理它。请帮帮我。
我的序列化器:
User = get_user_model()
Class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = (User.USERNAME_FIELD, )
我的观点:
@api_view(['GET'])
def UserViewSet(self, request):
if request.method == 'GET':
try:
user = User.objects.get(username=User.USERNAME_FIELD)
if User.DoesNotExist:
json = {}
json['message']= 'False'
return Response(json)
else:
json = {}
json['message']= 'True'
return Response(json)
答案 0 :(得分:2)
您可以使用APIView代替UserViewSet
和UserSerializer
。
class UserExistsView(APIView):
def get(self, request, *args, **kwargs):
# use this if username is in url kwargs
username = self.kwargs.get('username')
# use this if username is being sent as a query parameter
username = self.request.query_params.get('username')
try:
user = User.objects.get(username=username) # retrieve the user using username
except User.DoesNotExist:
return Response(data={'message':False}) # return false as user does not exist
else:
return Response(data={'message':True}) # Otherwise, return True