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



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

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

项目。网址

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')
]

用户.模型

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'.

用户视图(应用(

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

我无法将配置文件列表视图视为端点

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

序列化时应指定many=True

serializer = ProfileSerializer(profile,many=True)

您在这里混合了函数和基于类的视图定义:

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

您可以定义一个基于类的视图,如下所示:

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)

最新更新