美文网首页
错误 'dict_values' object does not

错误 'dict_values' object does not

作者: mpyl | 来源:发表于2019-07-23 17:07 被阅读0次

场景:我在学习中级 Django 应用:TweerApprover 的过程中,完成了 poster 的 urls.py、views.py 以及 post_tweet.html 和 than_you.html 两个页面后,开始操作起来,插入一条待审核的 tweet, 结果报错:

Traceback (most recent call last):
  ......省略多行
  File "/Users/mac/Documents/Django/myproject/poster/views.py", line 23, in post_tweet
    state='pending').aggregate(Count('id')).values()[0]
TypeError: 'dict_values' object does not support indexing

其实数据成功插入了,后面根据 state=pending 筛选数据后,对结果的处理出了问题。
贴出源码:

def thankyou(request):
    tweets_in_queue = Tweet.objects.filter(
        state='pending').aggregate(Count('id')).values()[0]
    return TemplateView.as_view(template_name ='thank_you.html',
                                extra_context = {'tweets_in_queue': tweets_in_queue})(request)

查了一下发现 stackvoerflow 是个好论坛,查询结果如下原链接

In python3.x, dict.values() doesn't return a list anymore -- it returns a dict_values object.
很明显,最后的返回结果不能当数组处理,得当字典处理才行。可我不清楚里面的 key 和 value呀!
怎么办?接下来你会发现 Django shell 真香。
cd 到项目目录下,然后 python3 manage.py shell进入

wd:myproject noduez$ python3 manage.py shell
Python 3.6.4 (v3.6.4:d48ecebad5, Dec 18 2017, 21:07:28) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from poster.models import Tweet
>>> from django.db.models import Count
>>> ti = Tweet.objects.filter(
...         state='pending').aggregate(Count('id'))
>>> ti
{'id__count': 0}
>>> ti['id__count']
0

这下不就清清楚楚,明明白白了么!
接下来改代码:不再用 .vlaues()[0] 直接改成['id__count'],即取key=id__countvalue

def thankyou(request):
  tweets_in_queue = Tweet.objects.filter(
      state='pending').aggregate(Count('id'))['id__count']
  return TemplateView.as_view(template_name ='thank_you.html',
                              extra_context = {'tweets_in_queue': tweets_in_queue})(request)

插入第一条数据:



插入第二条数据:


相关文章

网友评论

      本文标题:错误 'dict_values' object does not

      本文链接:https://www.haomeiwen.com/subject/zrdalctx.html