drf error, 'Expected a dictionary, but got QuerySet.'
I have a problem with drf function view, I am getting an serializer error like this: {'non_field_errors': [ErrorDetail(string='Invalid data. Expected a dictionary, but got QuerySet.', code='invalid')]} Here's my function based view:
@api_view(["GET","POST"])
def UserSearch(request):
selected_users = Profile.objects.all()
serializer = UserProfileSerializer(data=selected_users)
if serializer.is_valid():
return Response(data=serializer.data)
else:
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
My serializer:
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
fields = ('user','name','surname','gender','country','city','sport')
model = Profile
And Profile model:
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE)
name = models.CharField(max_length=50, blank=True)
surname = models.CharField(max_length=50, blank=True)
gender = models.CharField(max_length=50, blank=True)
country = models.CharField(max_length=50, blank=True)
city = models.CharField(max_length=50, blank=True)
sport = models.CharField(max_length=60, blank=True)
#date_of_birth = models.DateField()
def __str__(self):
return f"{self.name} {self.surname} from {self.city}"
your problem is here:
serializer = UserProfileSerializer(data=selected_users)
this must be
serializer = UserProfileSerializer(selected_users, many=True)
data=
should not be present here, data is only for python dict, when you want to serialize a python dict for example.
why many=True
, because you are querying more than 1 table rows, so it needs to be many
and your final code will be:
@api_view(["GET","POST"])
def UserSearch(request):
selected_users = Profile.objects.all()
serializer = UserProfileSerializer(selected_users, many=True) # <------
if serializer.is_valid():
return Response(data=serializer.data)
# that else was redundant
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)