我正在学习Django,并试图构建一个根据URL中给定的参数返回对象的端点。
目前,我有以下URL:
/api/v1/
作为根,返回:
GET /api/v1/
HTTP 200 OK
Allow: GET, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
{
"device-groups": "http://127.0.0.1:8000/api/v1/device-groups/"
}
/api/v1/device-groups/
返回所有设备组:
HTTP 200 OK
Allow: GET, POST, HEAD, OPTIONS
Content-Type: application/json
Vary: Accept
[
{
"device_group_name": "Default",
"group_uuid": "7465febe-7c46-4420-85a1-73dfe0af812c",
"color": "4286f4",
"is_default": true,
"customer": {
"customer_name": "Customer1",
"customer_uuid": "b3eb5d7d-d1a8-4997-a65b-28bed71b7cc6"
}
},
{
"device_group_name": "Default",
"group_uuid": "e12d02d0-7916-477e-b318-9680a38617db",
"color": "4286f4",
"is_default": true,
"customer": {
"customer_name": "Another customer",
"customer_uuid": "5b5dafab-c311-4f58-80f5-c50d77fcf8a5"
}
},
{
"device_group_name": "group of customer1",
"group_uuid": "c72e87b1-e7c8-4dcd-a9c7-4f6a016d7676",
"color": "#ffffff",
"is_default": false,
"customer": {
"customer_name": "Customer1",
"customer_uuid": "b3eb5d7d-d1a8-4997-a65b-28bed71b7cc6"
}
}
]
我想要一个/api/v1/device-groups/<customer_uuid>/
之类的端点,该端点返回与给定的customer_uuid相关的设备组。
我的serializers.py
:
class CustomerSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Customer
fields = ('customer_name', 'customer_uuid')
class DeviceGroupSerializer(serializers.HyperlinkedModelSerializer):
customer = CustomerSerializer(many=False, read_only=True)
class Meta:
model = DeviceGroup
fields = ('device_group_name', 'group_uuid', 'color', 'is_default', 'customer')
我的views.py
:
class DeviceGroupViewSet(viewsets.ModelViewSet):
serializer_class = DeviceGroupSerializer
queryset = DeviceGroup.objects.all()
我的urls.py
:
router = routers.DefaultRouter()
router.register(r'device-groups', views.DeviceGroupViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include(router.urls)),
]
我尝试像这样覆盖get_queryset
:
def get_queryset(self):
customer = self.request.GET['customer']
queryset = DeviceGroup.objects.filter(customer=customer)
return queryset
但是它导致:AssertionError: basename argument not specified, and could not automatically determine the name from the viewset, as it does not have a .queryset attribute.
要获得一个/api/v1/device-groups/<customer_uuid>/
端点,该端点仅显示与给定的customer_uuid相关的设备组,我需要更改什么?
编辑
Internal Server Error: /api/v1/device-groups/
Traceback (most recent call last):
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\utils\datastructures.py", line 77, in __getitem__
list_ = super().__getitem__(key)
KeyError: 'customer'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\core\handlers\exception.py", line 34, in inner
response = get_response(request)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\core\handlers\base.py", line 126, in _get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\core\handlers\base.py", line 124, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\views\decorators\csrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\viewsets.py", line 116, in view
return self.dispatch(request, *args, **kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\views.py", line 495, in dispatch
response = self.handle_exception(exc)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\views.py", line 455, in handle_exception
self.raise_uncaught_exception(exc)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\views.py", line 492, in dispatch
response = handler(request, *args, **kwargs)
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\rest_framework\mixins.py", line 40, in list
queryset = self.filter_queryset(self.get_queryset())
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\app\core\views.py", line
13, in get_queryset
customer = self.request.GET['customer']
File "C:\Users\Stevy\PycharmProjects\tapartisan-api\env\lib\site-
packages\django\utils\datastructures.py", line 79, in __getitem__
raise MultiValueDictKeyError(key)
django.utils.datastructures.MultiValueDictKeyError: 'customer'`
答案 0 :(得分:0)
路由器无法确定basename
。您必须在路由器中定义一个basename
。像这样
router.register(r'device-groups', views.DeviceGroupViewSet, base_name='device-groups')
base_name
实际上用于生成路由/ URL的名称。您可以详细了解here。
答案 1 :(得分:0)
我不熟悉DRF,但总的来说,为了基于参数获取对象,您必须:
1)定义URL时要记住要在构建端点时动态键入的customer_uuid 因此,在正则表达式的帮助下,您必须构建以下内容:
url(r'^/api/v1/device-groups/(?P<customer_uuid>\d+)/$', views.your_view, name='your_view')
正则表达式\ d +将匹配任意大小的整数。该整数将用于从数据库中检索客户。现在观察一下,我将正则表达式写为(?P \ d +),这是在告诉Django将值捕获到名为customer_uuid的关键字参数中。
2)定义视图功能
from django.shortcuts import render, get_object_or_404
from .models import Customer
def your_view(request, customer_uuid):
customer = get_object_or_404(Customer, pk=customer_uuid)
return render(request, 'customer.html', {'customer': customer})
希望有帮助
答案 2 :(得分:0)
如果在视图中定义不同的lookup_field,您应该得到想要的东西:
class DeviceGroupViewSet(viewsets.ModelViewSet):
serializer_class = DeviceGroupSerializer
queryset = DeviceGroup.objects.all()
lookup_field = 'customer_uuid'
或者也许您想看看这个documentation来考虑另一种方法。