Reputation: 1980
I have created Models UserProfile, serilzers and ModelViewSet like below. From below models I want to fetch loged in User profile details like state, city and adress etc
class UserProfile(models.Model):
user= models.OneToOneField(User,on_delete=models.CASCADE,related_name='userprofile');
state= models.CharField(max_length=200)
city= models.CharField(max_length=200)
add1= models.CharField(max_length=200)
add2= models.CharField(max_length=200)
postalcode= models.IntegerField()
country= models.CharField(max_length=200)
class UserProfileSerializer(serializers.ModelSerializer):
class Meta:
model = UserProfile
fields = ('state','city','country')
class UserProfileViewSet(viewsets.ModelViewSet):
queryset=UserProfile.objects.all()
serializer_class=UserProfileSerializer
def get(self, request):
userProfileObj = queryset.objects.filter(user_id=request.user.id)
serializer = self.get_serializer(userProfileObj)
return Response(serializer.data)
But for some reason, I am getting all user profile data instead of logged in user data, please let me know where I am doing wrong.
Upvotes: 1
Views: 5150
Reputation: 88429
You can do it by overriding the get_queryset()
method, as below
class UserProfileViewSet(viewsets.ModelViewSet):
queryset = UserProfile.objects.all()
serializer_class = UserProfileSerializer
def get_queryset(self):
if self.action == 'list':
return self.queryset.filter(user=self.request.user)
return self.queryset
Here the 'list'
refferes the api type, which is list api
. That means, it will return logged-in user's profile while you accessing the list api
Upvotes: 2
Reputation: 5249
ModelViewSet
implements the methods list
/retrieve
not get
.
Just overwrite get_queryset
instead. No need for creating serializer yourself. (There's no need to set queryset
attribute as well.)
Upvotes: 1