Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

QuerySet object has no attribute 'user' on Django Rest Framework

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'.

like image 283
Omid Zarinmahd Avatar asked Mar 11 '17 11:03

Omid Zarinmahd


1 Answers

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.

like image 96
Aniruddha Bhondwe Avatar answered Nov 19 '22 20:11

Aniruddha Bhondwe