1

I am building a Django app with a user model. the model: models.py

class User(AbstractUser):
    phone = models.CharField(max_length=20, blank=False)
    is_verified = models.BooleanField(default=False)
    address = models.CharField(max_length=200)
    city = models.CharField(max_length=50)
    country = models.CharField(max_length=50)
    is_verified = models.BooleanField(default=False)

serializers.py:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ('id', 'first_name', 'last_name')

views.py

class UserProfile(viewsets.ModelViewSet):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def get_queryset(self):
        return User.objects.get(id=self.request.user.id)

when going to the url /profile i get an error:

'User' object is not iterable

I validated that i have a User in the database with id = 1 and also that self.request.user.id is int(1)

appreciate any insight

I tried to get the user profile data from the object user. i was expecting to get a result with the user serialized i.e {id: 1, first_name="X", last_name="Y"} i actually got a response with 'User' object is not iterable

Slipyster
  • 13
  • 2
  • in `get_queryset` reutrn `User.objects.filter(id=self.request.user.id)`, use filter to get all records [django-filter-vs-get-in-models](https://stackoverflow.com/questions/15251401/django-filter-vs-get-in-models) – sahasrara62 May 05 '23 at 18:43

2 Answers2

0

You should change your code to return a queryset that can be iterated over in order to correct this mistake. To accomplish this, you can encapsulate the returned object in a list as seen below:

def get_queryset(self):
   return User.objects.filter(id=self.request.user.id)

This will produce a queryset that can be iterated over and contains a single User object with the given id.

Papan Sarkar
  • 112
  • 6
0

A ModelViewSet is not suited for this task, since a simple GET will return a list, perhaps a list with one element, but a list. You only retrieve a single element if you add a /pk suffix in the URL.

You can work with a RetrieveAPIView:

from rest_framework.generics import RetrieveAPIView


class UserProfile(RetrieveAPIView):
    permission_classes = (IsAuthenticated,)
    serializer_class = UserSerializer

    def get_object(self):
        return self.request.user
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555