I cannot serialize a model to get results while performing requests on Django Rest Framework.
class Karfarma(models.Model):
user = models.OneToOneField(User, related_name='karfarma', on_delete=models.CASCADE)
mobile = models.TextField(max_length=11)
validation_number = models.TextField(max_length=5, blank=True, default=None)
phone_number = models.TextField(max_length=10, blank=True, default=None)
datetime_join_persian = models.DateTimeField(default=None, null=True)
def __unicode__(self):
return "%s %s" % (self.user.first_name, self.user.last_name)
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'
class UserList(APIView):
queryset = User.objects.all()
def get(self, request):
users = User.objects.all()
serializer = UserSerializer(users)
return Response(serializer.data)
Here's the reduced version of the error which I get when I perform the request:
AttributeError: Got AttributeError when attempting to get a value for field
user
on serializerUserSerializer
. The serializer field might be named incorrectly and not match any attribute or key on theQuerySet
instance. Original exception text was: 'QuerySet' object has no attribute 'user'.
Whenever you are trying to pass a queryset to a serializer always pass it with UserSerializer(users,many=True)
. If you just want to pass a single user object you can use User.objects.get(some_attribue=something)
and then pass that object to the serializer without the many=True
flag.
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