8
votes

i extend django user model in some way but can not serialize it and get results

my model

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)

my serializer

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = '__all__'

my view

class UserList(APIView):
    queryset = User.objects.all()

    def get(self, request):
        users = User.objects.all()
        serializer = UserSerializer(users)
        return Response(serializer.data)

but i got this error

AttributeError at /api/members/

'QuerySet' object has no attribute 'users'

Request Method: GET

Request URL: http://127.0.0.1:8000/api/members/

Django Version: 1.8

Exception Type: AttributeError

2
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... - Laurent S
@LaurentS I edit my question - Omid Zarin
try serializer = UserSerializer(users,many=True) - Aniruddha Bhondwe

2 Answers

43
votes

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.

-7
votes

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