是否可以在 Django rest-framework URL 中传递外键 ID?

Is it possible to pass the foreign key id in Django rest-framework URL?

我在 Django Rest Framework 中使用路由器并尝试基于外键创建动态 URL。我的 urls.py 文件看起来像这样,

router = routers.DefaultRouter()
router.register('user/<int:user_id>/profile', ProfileViewSet, 'profile')

urlpatterns = router.urls

我的 models.py 文件如下所示,

class Profile(models.Model):
    user = models.ForeignKey(
        User, related_name='profile_user', on_delete=models.CASCADE)
    character = models.CharField(max_length=10, null=True, blank=True)

我的 views.py 文件如下所示,

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer

我在所有 (post, put, get) 请求中收到 404 错误。是否有针对此类实施的任何可能的简单解决方案?

编辑

这是我的结果 URL(GET 请求):

http:localhost:8000/user/1/profile

我得到以下结果:

Page not found (404)
Request Method: GET
Request URL:    http://localhost:8000/user/1/profile

更改此行

router.register('user/<int:user_id>/profile', ProfileViewSet, 'intensity_classes')

使用这个

router.register(r'users', ProfileViewSet, basename='user')

然后是列表视图

http://127.0.0.1:8000/users/ -> 配置文件列表

查看详情

http://127.0.0.1:8000/users/13 ->这里13是配置文件id,可以更新删除配置文件实例

更改正则表达式格式的 URL 后,我的问题就解决了。而不是这个,

router.register('user/<int:user_id>/profile', ProfileViewSet, 'profile')

这是我写的,

router.register(r'user/(?P<user_id>\d+)/profile', ProfileViewSet, 'profile')