9

I cannot serialize a model to get results while performing requests on Django Rest Framework.

models.py

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)

serializers.py

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'

views.py

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 serializer UserSerializer. The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance. Original exception text was: 'QuerySet' object has no attribute 'user'.

3
  • can you add urls.py to your question, and probably views.py as well. I don't understand the link between your serializer and your model... Commented Mar 11, 2017 at 12:03
  • @LaurentS I edit my question Commented Mar 11, 2017 at 12:30
  • try serializer = UserSerializer(users,many=True) Commented Mar 11, 2017 at 12:53

2 Answers 2

49

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.

Sign up to request clarification or add additional context in comments.

2 Comments

It helped me solve my problem. Thank you sir @Aniruddha Bhondwe
So, we have to use many=True in views too! This simple suggestion solved my problem, Thanks
-7

finally I found what was wrong view was the problem when ever you want to get list of objects you should pass argument many=True to the serializer. the problem was this

1 Comment

Did you seriously accept your answer which is just a bad copy of a previously posted correct answer?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.