![](/img/trans.png)
[英]Django: TypeError - argument of type 'QuerySet' is not iterable
[英]argument of type 'QuerySet' is not iterable Django error
在我的 web 應用程序中,我有一個朋友功能,但是其中一個 if 語句會產生錯誤
這是我的 UserProfileInfo model
class UserProfileInfo(models.Model):
connection = models.ManyToManyField(User,blank=True,related_name='follow_profile')
現在這是我的觀點:
def friend_actions(request,username=None):
current_user = request.user.userprofileinfo
user = request.user
# username = get("username")
username = User.objects.get(username=username)
other_user = get_object_or_404(UserProfileInfo,user__username=username)
# other_user = UserProfileInfo.objects.get(username=username)
url = other_user.get_absolute_url()
if other_user in current_user.connection.all():
current_user.connection.remove(other_user)
else:
current_user.connection.add(other_user)
return HttpResponseRedirect(url)
但是,這會產生以下錯誤:
'QuerySet' 類型的參數不可迭代
完整回溯
Traceback:
File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\exception.py" in inner
34. response = get_response(request)
File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response
115. response = self.process_exception_by_middleware(e, request)
File "C:\Users\User\.virtualenvs\interests-site-Ho6yLlHE\lib\site-packages\django\core\handlers\base.py" in _get_response
113. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Users\User\interests-site\interests-drf\mainapp\views.py" in friend_actions
453. if other_user in current_user.connection.all():
Exception Type: TypeError at /mainapp/profile/donnellan0007/connect/
Exception Value: argument of type 'QuerySet' is not iterable
我想知道如何阻止此錯誤的發生。 我整天都被它難住了
這似乎是一個不時出現的錯誤,也就是 Heisenbug!
QuerySet 確實是一個可迭代的( https://github.com/django/django/blob/master/django/db/models/query.py#L271 )
Django 的論壇有一些關於此的信息 -
https://code.djangoproject.com/ticket/26600 https://github.com/PyCQA/pylint-django/issues/117
一般來說,這個問題似乎是因為在iter中拋出了異常(除了 StopIteration 之外)。
您可以使用以下路線之一 -
強制查詢集列出(不推薦)
使用條件過濾連接。 在您的情況下,使用過濾器在連接中搜索 other_user
返回 values_list 值而不是 Queryset 並對其執行“in”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.