Py学习  »  Django

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

Curtis Banks • 5 年前 • 1428 次点击  

我很难理解如何用Django REST框架显示基于函数的视图url。

我已经在下面设置了我的项目,但是由于某些原因,当MovieListViewSet工作时,我无法显示端点。

项目.url

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

用户.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',
        )

我有意见 bio location 因为当它们被取消注释时,我会收到这个消息。

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)

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

有人能告诉我,在django rest框架中显示这个端点时我做错了什么吗。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/51565
 
1428 次点击  
文章 [ 1 ]  |  最新文章 5 年前
JPG
Reply   •   1 楼
JPG    5 年前

您应该指定 many=True 序列化时。

serializer = ProfileSerializer(profile, many=True)