英文:
Django app getting the error "TypeError: 'dict_keys' object is not subscriptable"
问题
以下是代码的翻译部分:
这是视图:
class UserViewSet(viewsets.ViewSet):
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = User.objects.all()
user = get_object_or_404(queryset, pk=pk)
serializer = UserSerializer(user)
return Response(serializer.data)
URLs:
from django.urls import path
from .views import *
from rest_framework import routers
userl = UserViewSet.as_view({'get': 'list'})
userd = UserViewSet.as_view({'get': 'retrieve'})
router = routers.SimpleRouter()
router.register('users', UserViewSet, basename='user')
urlpatterns = [
path('users/', userl, name='user-list'),
path('users/<int:pk>/', userd, name='user-detail'),
path('register', RegisterUserAPIView.as_view()),
path('login/', LoginAPIView.as_view()),
path('logout', LogoutAPIView.as_view()),
path('products', ProductsViewSet.as_view({'get': 'list'})),
]
跟踪信息:
File "C:\Users\User\Desktop\erkin2\venv\lib\site-packages\routers\router.py", line 27, in db_for_read
return settings.DATABASES.keys()[0]
TypeError: 'dict_keys' object is not subscriptable
我尝试使用`keys()`,但然后它说:
> 函数没有属性keys()。
英文:
Here is the views:
class UserViewSet(viewsets.ViewSet):
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
queryset = User.objects.all()
user = get_object_or_404(queryset, pk=pk)
serializer = UserSerializer(user)
return Response(serializer.data)
urls:
from django.urls import path
from .views import *
from rest_framework import routers
userl = UserViewSet.as_view({'get': 'list'})
userd = UserViewSet.as_view({'get': 'retrieve'})
router = routers.SimpleRouter()
router.register(r'users', UserViewSet, basename='user')
urlpatterns = [
path('users/', userl, name='user-list'),
path('users/<int:pk>/', userd, name='user-detail'),
path('register',RegisterUserAPIView.as_view()),
path('login/', LoginAPIView.as_view()),
path('logout', LogoutAPIView.as_view()),
path('products', ProductsViewSet.as_view({'get': 'list'})),
]'login/', LoginAPIView.as_view()),
path('logout', LogoutAPIView.as_view()),
path('products', ProductsViewSet.as_view({'get': 'list'})),
]
Traceback:
File "C:\Users\User\Desktop\erkin2\venv\lib\site-packages\routers\router.py", line 27, in db_for_read
return settings.DATABASES.keys()[0]
TypeError: 'dict_keys' object is not subscriptable
I've tried using keys()
but then it says:
> function has no attribute keys().
答案1
得分: 1
明显并且也许逆直觉的是,字典的 `keys()` 方法并不返回一个键列表。让我们检查一下:
```python
d = {'a': 1, 'b': 2}
print(d.keys())
>>> dict_keys(['a', 'b'])
print(type(d.keys()))
>>> <class 'dict_keys'>
d.keys()[0]
>>> TypeError: 'dict_keys' 对象不可索引
这并不总是如此。在Python 2中,keys()
方法确实返回一个列表。参见这个旧问题。
要获取键的实际列表,您可以在字典上调用 list()
:
print(list(d))
>>> ['a', 'b']
然后索引将按预期工作:
print(list(d)[0])
>>> a
因此,您可能希望将行 return settings.DATABASES.keys()[0]
更改为:
return list(settings.DATABASES)[0]
<details>
<summary>英文:</summary>
Apparently and perhaps counter-intuitively, the `keys()` method for dictionaries does not return a list of keys. Let's check:
```python
d = {'a': 1, 'b': 2}
print(d.keys())
>>> dict_keys(['a', 'b'])
print(type(d.keys()))
>>> <class 'dict_keys'>
d.keys()[0]
>>> TypeError: 'dict_keys' object is not subscriptable
This was not always so. In Python 2, the keys()
method did return a list. See this old question.
To get an actual list of the keys, you can call list()
on the dictionary:
print(list(d))
>>> ['a', 'b']
Then indexing works as expected:
print(list(d)[0])
>>> a
So you may want to change the line return settings.DATABASES.keys()[0]
to this:
return list(settings.DATABASES)[0]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论