我想创建一个API端点,通过djangoRestAPI中的属性“user_id”获取User和User Profile,user_id将由客户端发送

jqjz2hbq  于 2023-08-08  发布在  Go
关注(0)|答案(1)|浏览(116)

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")

]


我希望我的响应在JSON格式,以便我可以使用它在Android应用程序。我浏览了许多博客和Stackoverflow的答案,但其中任何一个都没有给予期望的结果
简而言之,我只希望客户端发送一个userid并以json格式获取User和UserProfile
获取“TypeError:“User”对象不可作为输出迭代

envsm3lx

envsm3lx1#

你需要大量改进你的代码。无论如何,为了让用户简单地从ProfileSerializer中删除many=True

相关问题