我是Django REST框架的新手,尽管做了两次教程并阅读了大量文档,但我无法确切地知道如何处理/访问DRF ViewSet中URL的参数。
我的网址如下:
/api/v1/user/<user-id>/<age>/update
在我的基础urls.py中我有urlpattern:
url(r'^api/v1/', include('api.urls'))
在api / urls.py中我有:
from django.conf.urls import url, include
from rest_framework import routers
from api import views
router = routers.DefaultRouter()
router.register(r'user', views.UserViewSet)
urlpatterns = [
url(r'^', include(router.urls))
]
我的问题是我的UserViewSet应该如何处理url,提取用户ID和年龄字段,以及更新UserDetails模型以便给定用户具有给定的年龄?
我的模型尚未创建,但看起来像这样:
class UserDetails(models.Model):
user = models.ForeignKey(User)
age = models.BigIntegerField(blank=True, null=True)
答案 0 :(得分:0)
In the serializers.py adde the ParameterisedHyperlinkedIdentityField as a serializer.
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = ParameterisedHyperlinkedIdentityField(view_name='user-detail', lookup_fields=(('id', 'id'), ('age', 'age')), read_only=True)
class Meta:
model = UserDetails
from .viewsets import UserViewSet
user_list = UserViewSet.as_view({'get':'list'})
user_detail = UserViewSet.as_view({'get':'retrieve'})
urlpatterns= [
url(r'^user/(?P<id>\d+)/(?P<age>[-\w\d]+)/update/$', user_detail, name='user-detail')
]
class UserViewset(viewsets.ModelViewSet):
lookup_field = 'id'
serializer_class = UserSerializer
queryset = UserDetails.objects.all()