Search code examples
djangodjango-modelsdjango-rest-frameworkdjango-viewsdjango-serializer

I want to create a API endpoint to fetch User and User Profile by attribute "user_id" in djangoRestAPI, user_id will be sent by the client


models.py

class User_profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=50, blank=False)
    phone = models.CharField(max_length=20, blank=False)
    profileImg = models.ImageField(upload_to='User/Profile_Picture', default='User/Profile_Picture/logo.png')
    city = models.CharField(max_length=50, blank=False, default=None)
    state = models.CharField(max_length=50, blank=False, default=None)
    birthdate = models.DateField(blank=False)
    bio = models.TextField(max_length=1000, blank=True, null=True)
    privacy = models.CharField(max_length=20, choices=PRIVACY_CHOICES, default='public', blank=False)
    requests = models.ManyToManyField(User, related_name='follow_request_user', default=None, blank=True)
    verified = models.BooleanField(default=False, blank=False)
    following_user = models.ManyToManyField(User, related_name='following_user', default=None, blank=True)

    followers = models.ManyToManyField(User, related_name='user_followers', default=None, blank=True)

    objects = models.Manager()

    def __str__(self):
        return self.name

serializer.py

from rest_framework import serializers
from .models import *


class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = User_profile
        fields = "__all__"

**api_views.py **

from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework.views import APIView
from .serializer import *
from .models import *


class ProfileAPI(APIView):
    def get(self, request, *args, **kwargs):
        user = get_object_or_404(User, id=kwargs['user_id'])
        profile_serializer = ProfileSerializer(user,many=True)
        return Response(profile_serializer.data)

**api_urls.py **

from django.urls import path

from . import api_views

urlpatterns = [
    path('profile/<user_id>', api_views.ProfileAPI.as_view(), name="profile")


]

I want my response in JSON format so that i can use it in android app. I went through many blogs and Stackoverflow answers but any of that didn't give desired output

In Short i just expect that client sends a userid and get User and UserProfile in json format

getting "TypeError: 'User' object is not iterable" as output


Solution

  • If you want solution to your code just remove many=True from ProfileSerializer.

    many=True is passed, when we pass list of model objects to serializer, and we want response in form of LIST.


    And this is more concise implementation for above usecase

    api_views.py

    from rest_framework.response import Response
    from rest_framework.generics import RetrieveAPIView
    from .serializer import *
    from .models import *
    
    class ProfileAPI(RetrieveAPIView):
        serializer_class = ProfileSerializer
        queryset = User_profile.objects.all()
    

    urls.py

    urlpatterns = [
        path('profile/<int:pk>', api_views.ProfileAPI.as_view(), name="profile")
    
    ]