2016-07-26 20 views
-1

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' 

我該如何解決這個問題?

感謝您閱讀我的問題。

+0

我不明白你的代碼。 'list(chain(''+','+'list_i'))''做了什麼?如果你有一個查詢集「list_i」,爲什麼你在'list(chain(''+','+'list_i'))''中將它作爲一個字符串? –

+0

另外,你是什麼意思'獲取queryset'總和?什麼東西? –

+0

我希望list_1 + list_2 + list_3 ...直到帖子的總數爲gte = 5。因爲我是編程新手,所以我很難遵循python itertools規則。 'list(chain(''+','+'list_i'))'是我使用鏈函數的努力。有沒有其他好方法? – touchingtwist

回答

2

看起來好像你在字符串值和文本值之間有嚴重的斷開。

In [126]: x = 3 

In [127]: print("x") 
x 

In [128]: print(x) 
3 

In [129]: print(str(x)) 
3 

基於您的代碼,我敢肯定你認爲print("x")會打印出3。它的寫作方式永遠不會是真的。我說,因爲你只從自己的錯誤中一般有

i=1 
while i: 
    list_i = Post.objects.filter(title__startswith="i") 

一旁,看着你的其他代碼,我敢肯定,你希望這個返回Post s表示與1開始。它不會,它只會返回以'i'開頭的帖子。

在這裏,您還創建了一個變量i,並且您使用的是while i,但您從不在任何地方更改i。如果你正在尋找的是確保你的帖子列表中至少有5個項目,那麼你會發現這一切都是錯誤的。

首先,你需要的是一個文章列表:

post_list = [] 

如果你想在文章標題與1然後2啓動,等等,你將需要一個計數器號進行過濾,太:

count = 0 

現在,你需要循環,而列表中有少於5個元素:

while len(post_list) < 5: 

然後你需要將東西附加到列表中。什麼東西?你得到的帖子。但是,我們也將要顛簸起來,通過所以我們不會將相同的帖子,每次數:

count += 1 
    post_list.extend(Post.objects.filter(title__startswith=str(count))) 

把所有在一起,你會得到:

高清post_list(請求) :

post_list = [] 
count = 0 
while len(post_list) < 5: 
    count += 1 
    post_list.extend(Post.objects.filter(title__startswith=str(count))) 

return JsonResponse(serializers.serialize('json', post_list), safe=False) 

然而,有一件事我們還沒有考慮 - 如果你從來沒有得到比5級的職位嗎?如果你的系統只有4個呢?這將永遠不會結束 - 你將進入一個無限循環。所以我們應該增加另一個哨兵 - 我們知道從小學數:

1,2,3,4,5,6,7,8,9, 
10, 
11, 
12, 
... 
19, 
20, 
21, 
... 

每個9以上的數字將開始以數字1-9。所以我們可以肯定地說,如果我們的計數達到10+以上,那麼我們的一個過濾器已經可以檢測到它了。即使222392138902×10^20打頭2.因此,我們應該修改我們的while條件是:

while count < 10 and len(post_list) < 5: 

,我們還會有一個,我覺得你想要做什麼,除非你有一些不同的想法的解決方案關於過濾。

+0

對我來說這是一個很好的演講。如你所想,英語不是我的第一語言,所以我在閱讀和理解英語寫作方面遇到麻煩。但你的解釋對我來說很好。謝謝。這對我非常有幫助。 – touchingtwist

+0

如果我的回答是解決您的問題的最佳方案,則應通過單擊左側的複選標記將其標記爲<--- –

1

您不應該使用chainchain方法將鏈名單在一起,但你不希望所有的人都在一起,所以你應該只使用普通列表的方法:

def post_list(request): 
    result = [] 
    i = 1 
    while True: 
     list_i = Post.objects.filter(title__startswith=str(i)) 
     result.extend(list_i) 
     if len(result) >= 5: 
      result = result[:5] 
      break 
     i += 1 
    return JsonResponse(serializers.serialize('json', result), safe=False) 

沒有違法,但讀你的代碼,我覺得你是缺少一些基本知識的Python /編程。我建議你在跳入Django開發之前學習一些關於python的基礎知識,這會爲你節省很多時間來找出這樣的東西。

+0

哇,非常非常謝謝。你是對的。我會記住你的建議。謝謝。 – touchingtwist

相關問題