views.py如何獲取queryset列表的總和並使jsonresponse?
from itertools import chain
def post_list(request):
i=1
while i:
list_i = Post.objects.filter(title__startswith="i")
post_list = list(chain('' + ',' + 'list_i'))
if len(post_list) >= 5 :
break
return JsonResponse(serializers.serialize('json', post_list), safe=False)
我想使post_list即LIST_1,list_2,..,list_i並使之系列化的總和。
但它給我AttributeError如下。
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/
Django Version: 1.9.7
Python Version: 3.5.2
Installed Applications:
[...I omitted]
Installed Middleware:
[...I omitted]
Traceback:
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
149. response = self.process_exception_by_middleware(e, request)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/handlers/base.py" in get_response
147. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/keepair/djangogirls/blog/views.py" in post_list
33. return JsonResponse(serializers.serialize('json', post_list), safe=False)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/serializers/__init__.py" in serialize
129. s.serialize(queryset, **options)
File "/home/keepair/djangogirls/myvenv/lib/python3.5/site-packages/django/core/serializers/base.py" in serialize
83. concrete_model = obj._meta.concrete_model
Exception Type: AttributeError at/
Exception Value: 'str' object has no attribute '_meta'
我該如何解決這個問題?
感謝您閱讀我的問題。
我不明白你的代碼。 'list(chain(''+','+'list_i'))''做了什麼?如果你有一個查詢集「list_i」,爲什麼你在'list(chain(''+','+'list_i'))''中將它作爲一個字符串? –
另外,你是什麼意思'獲取queryset'總和?什麼東西? –
我希望list_1 + list_2 + list_3 ...直到帖子的總數爲gte = 5。因爲我是編程新手,所以我很難遵循python itertools規則。 'list(chain(''+','+'list_i'))'是我使用鏈函數的努力。有沒有其他好方法? – touchingtwist