2014-02-08 163 views
1

我在執行查詢時遇到問題,它給了我錯誤。但是,如果從控制檯Django的運行,我回到正確'QCombination'對象不可迭代

結果在Python Shell(蟒蛇manage.py殼)

>>> from api.models import User 
>>> from django.db.models import Q 
>>> User.objects.filter(Q(username__contains='lucas')) 
[<User: @lucas>, <User: @lucasfuentes>, <User: @lucas_gasolero>] 

在views.py

def search(req, keyword): 
    users = User.objects.filter(
     Q(username__contains='lucas') | Q(name__contains='lucas') 
    ) 
    [..] 

ERROR: 'QCombination'對象是不可迭代的

Traceback: 
File "[..]/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 
    115. response = callback(request, *callback_args, **callback_kwargs) 

File "[..]/api/views.py" in search 
    84. Q(username__contains='lucas') | Q(name__contains='lucas') 

File "[..]/lib/python2.7/site-packages/django/db/models/manager.py" in filter 
    155. return self.get_query_set().filter(*args, **kwargs) 

File "[..]lib/python2.7/site-packages/django/db/models/query.py" in filter 
    669. return self._filter_or_exclude(False, *args, **kwargs) 

File "[..]lib/python2.7/site-packages/django/db/models/query.py" in _filter_or_exclude 
    687. clone.query.add_q(Q(*args, **kwargs)) 

File "[..]lib/python2.7/site-packages/django/db/models/sql/query.py" in add_q 
    1271. can_reuse=used_aliases, force_having=force_having) 
File "[..]lib/python2.7/site-packages/django/db/models/sql/query.py" in add_filter 
    1066. arg, value = filter_expr 

Exception Type: TypeError at /v1/search/as/ 
Exception Value: 'QCombination' object is not iterable 
+1

在shell中它不是同一個查詢。你有沒有在shell中嘗試過Q(username__contains ='lucas')| Q(name__contains = '盧卡斯')'? – warvariuc

+0

是一樣的。在views.py'Q(username__contains ='lucas') - 錯誤'Q'對象不可迭代。在shell中'Q(username__contains ='lucas')| Q(name__contains ='lucas')'沒有錯誤! :( – lucasmg

+0

@lucasmg,你是否仍然有同樣的問題? – Nil

回答

0

由於沒有人回答,我會嘗試一些。確保你輸入正確的User。在Django documentation,它的進口是這樣的:

from django.contrib.auth.models import User 

我們可以看到,你在你的shell使用from api.models import User,但我們不看你如何在你的意見導入User。我知道它在shell中與「壞」導入一起工作,但仍然要確保在這兩種情況下使用正確的導入並告訴我們結果。如果它仍然不起作用,我不知道,對不起!

0

像@Nil所說的,但在views.py中檢查Q導入。它可能不是django.db.models.Q