当循环访问Django中的用户对象的查询集时,当我试图访问另一个模型的每个与用户对象相关的集合时,我总是得到一个AttributeError。在
模型.py
class List(models.Model):
def __unicode__(self):
return self.title
title = models.CharField(max_length=225)
owner = models.ForeignKey(User, related_name='owned_lists')
实用工具/电子邮件.py
^{pr2}$当我的“daily_completed”函数运行时,当试图查找每个用户的“owned_list”时,它会触发以下AttributeError:
AttributeError:'User'对象没有属性'owned'u list'
但是当我将“daily_completed”函数改为只代表一个用户运行,而不是遍历所有用户时,它可以正常工作。在
示例实用程序/电子邮件.py
def daily_completed():
user = User.objects.get(pk=1)
# get one big QuerySet
all_lists = user.owned_lists.all()
print all_lists
上面的函数工作正常,不会触发任何AttributeError。在
有人知道为什么会这样吗?我真的很感谢你的帮助!提前谢谢。在
以下是整个回溯:
Traceback (most recent call last):
File "C:\projects\slothnote\env\lib\site-packages\celery\app\trace.py", line 240, in trace_task
R = retval = fun(*args, **kwargs)
File "C:\projects\slothnote\env\lib\site-packages\celery\app\trace.py", line 437, in __protected_call__
return self.run(*args, **kwargs)
File "C:\projects\slothnote\env\slothnote\lists\tasks.py", line 14, in daily_completed_tasks_email
daily_completed()
File "C:\projects\slothnote\env\slothnote\lists\emails.py", line 30, in daily_completed
all_lists = user.owned_lists.all()
AttributeError: 'User' object has no attribute 'owned_lists'
更新:
不知道为什么,但是当我改变循环的变量名时。请看这里:
all_users = User.objects.all()
for each_user in all_users:
# get one big QuerySet
all_lists = each_user.owned_lists.all()
print all_lists
上面的块按预期执行。所以,我的问题解决了,但我还是很想知道为什么它以前没用。在
目前没有回答
相关问题 更多 >
编程相关推荐