如何在 django rest 框架中显示基于函数的视图端点

How to display function based view endpoint in django rest frameworks

我很难理解如何使用 Django REST FRAMEWORK 显示基于函数的视图 URL。

我的项目设置如下,但由于某些原因,我无法在 MovieListViewSet 工作时显示端点。

PROJECT.URLS

from users import views

router = routers.DefaultRouter()
router.register(r'movies', MovieListViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('admin/', admin.site.urls),
    path('profile/', views.ProfileList, name='ProfileList')
]

users.model

User = settings.AUTH_USER_MODEL

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    bio = models.TextField(max_length=500)
    location = models.CharField(max_length=50)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')

    def __str__(self):
        return self.user.username

序列化程序

from rest_framework import serializers
from users.models import Profile

class ProfileSerializer(serializers.ModelSerializer):
    user = serializers.StringRelatedField(read_only=True)

    class Meta:
        model = Profile
        fields = (
            'id',
            'user',
            #'bio',
            #'location',
            'image',
        )

我有评论 biolocation 因为当他们取消评论时,我收到这条消息。

Got AttributeError when attempting to get a value for field `bio` on serializer `ProfileSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'bio'.

users.views(应用程序)

@api_view(["GET"])
def ProfileList(APIView):
    profile = Profile.objects.all()
    serializer = ProfileSerializer(profile)
    return Response(serializer.data)

我无法将 ProfileList 视图视为端点

有人可以指出我在将此端点显示到 django rest 框架时做错了什么。

你应该在序列化时指定many=True

serializer = ProfileSerializer(profile, <b>many=True</b>)

您在此处混淆了函数和基于 class 的视图定义:

@api_view(["GET"])
def ProfileList(APIView):
    profile = Profile.objects.all()
    serializer = ProfileSerializer(profile)
    return Response(serializer.data)

要么像这样定义一个基于 class 的视图:

class ProfileView(APIView):
    profile = Profile.objects.all()
    serializer = ProfileSerializer

    def list(request):
       return Response(self.serializer_class(self.get_queryset(), many=True).data)

或者像这样的函数基础视图:

@api_view(["GET])
def profile_list(request):
   return Response(ProfileSerializer(Profile.objects.all(), many=True).data)