Django应用程序出现错误:”TypeError: ‘dict_keys’对象不可订阅”

huangapple go评论71阅读模式
英文:

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({&#39;get&#39;: &#39;list&#39;})
userd = UserViewSet.as_view({&#39;get&#39;: &#39;retrieve&#39;})

router = routers.SimpleRouter()
router.register(r&#39;users&#39;, UserViewSet, basename=&#39;user&#39;)

urlpatterns = [
  path(&#39;users/&#39;, userl, name=&#39;user-list&#39;),
  path(&#39;users/&lt;int:pk&gt;/&#39;, userd, name=&#39;user-detail&#39;),
  path(&#39;register&#39;,RegisterUserAPIView.as_view()),
  path(&#39;login/&#39;, LoginAPIView.as_view()),
  path(&#39;logout&#39;, LogoutAPIView.as_view()),
  path(&#39;products&#39;, ProductsViewSet.as_view({&#39;get&#39;: &#39;list&#39;})),

]&#39;login/&#39;, LoginAPIView.as_view()),
  path(&#39;logout&#39;, LogoutAPIView.as_view()),
  path(&#39;products&#39;, ProductsViewSet.as_view({&#39;get&#39;: &#39;list&#39;})),

]

Traceback:

  File &quot;C:\Users\User\Desktop\erkin2\venv\lib\site-packages\routers\router.py&quot;, line 27, in db_for_read
    return settings.DATABASES.keys()[0]
TypeError: &#39;dict_keys&#39; 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&#39;s check:
```python
d = {&#39;a&#39;: 1, &#39;b&#39;: 2}

print(d.keys())
&gt;&gt;&gt; dict_keys([&#39;a&#39;, &#39;b&#39;])

print(type(d.keys()))
&gt;&gt;&gt; &lt;class &#39;dict_keys&#39;&gt;

d.keys()[0]
&gt;&gt;&gt; TypeError: &#39;dict_keys&#39; 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))
&gt;&gt;&gt; [&#39;a&#39;, &#39;b&#39;]

Then indexing works as expected:

print(list(d)[0])
&gt;&gt;&gt; a

So you may want to change the line return settings.DATABASES.keys()[0] to this:

return list(settings.DATABASES)[0]

huangapple
  • 本文由 发表于 2023年4月7日 04:14:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/75953425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定