django - 无法使用 View 名称 (django-rest-framework) 解析超链接关系的 URL

标签 django django-rest-framework

问题 :

我收到这样的错误。

ImproperlyConfigured at /api/users/

Could not resolve URL for hyperlinked relationship using view name "user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.



我读了这个 post但它没有用。

序列化程序.py
class UserSerializer(serializers.ModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='user-detail',
                                               lookup_field='profile')

    class Meta:
        model = User
        fields = ('id', 'username', 'first_name', 'last_name', 'url')


class UserProfileSerializer(serializers.ModelSerializer):
    user = serializers.ReadOnlyField(source='user.username')

    class Meta:
        model = UserProfile
        fields = "__all__"
        # user = serializers.ReadOnlyField(source='owner.username')

    def create(self, validated_data):
        pass

    def update(self, instance, validated_data):
        pass

网址.py
user_profile_list = UserProfileViewSet.as_view({
    'get': 'list',
    'post': 'create'
})
user_profile_detail = UserProfileViewSet.as_view({
    'get': 'retrieve',
    'put': 'update',
    'patch': 'partial_update',
    'delete': 'destroy'
})
user_list = UserViewSet.as_view({
    'get': 'list'
})
user_detail = UserViewSet.as_view({
    'get': 'retrieve'
})
user_profiles_detail = UserViewSet.as_view({
    'get': 'profile'
})

router = DefaultRouter()
router.register(r'userprofiles', views.UserProfileViewSet)
router.register(r'users', views.UserViewSet)

urlpatterns = [
    url(r'^', include(router.urls))
]

View .py
class UserProfileViewSet(viewsets.ModelViewSet):
    """
    This viewset automatically provides `list`, `create`, `retrieve`,
    `update` and `destroy` actions.
    """
    queryset = UserProfile.objects.all()
    serializer_class = UserProfileSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,
                          IsOwnerOrReadOnly,)
    pagination_class = LimitTenPagination

    @detail_route(renderer_classes=[renderers.JSONRenderer])
    def perform_create(self, serializer):
        serializer.save(user=self.request.user)


class UserViewSet(viewsets.ReadOnlyModelViewSet):
    """
    This viewset automatically provides `list` and `detail` actions
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

来自我的 models.py 的片段
class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')

我试过的:

我尝试更改 user-detailapi:user-detail (是的 api 命名空间确实存在于主 urls.py 文件中)

最佳答案

  • 查看文档,我相信您必须使用 HyperLinkedRelatedField .另见 this related SO post .
  • 您在序列化程序字段定义中混淆了参数。我认为应该是:
    class UserSerializer(serializers.ModelSerializer):
        url = serializers.HyperlinkedRelatedField(view_name='api:userprofile-detail',
                                                  source='profile')
    

  • 编辑 :

    已添加 namespace api

    关于django - 无法使用 View 名称 (django-rest-framework) 解析超链接关系的 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48360278/

    相关文章:

    django - 我可以通过pk(字符串)获取django模型对象吗?

    django - 我把 "WSGIPassAuthorization On"放在哪里?

    python - 创建后URL不存在

    python - 在 Apache 中运行 Django Rest Framework

    django - 类型对象 'X'没有属性 'objects'

    python - ManytoMany 与 django Rest 相关

    Django-Rest-Framework - 嵌套对象和序列化器,如何?

    django - 我应该为标签使用 ArrayField 还是 ManyToManyField

    python - Django、 celery 、Redis、RabbitMQ : Chained Tasks for Fanout-On-Writes

    python - Django/Python 更新字段值(在模型保存期间)