QuerySet相关
今天在用django制作一个访问用户参与的项目表(类似于shoppingcar)时,遇到了如下的报错:
File "D:\xxxx\xxx\xxxxxxxx\xxxxx\views.py", line 375, in IwannaAttendThis
new_player.project_deadline = Project.project_deadline
AttributeError: 'QuerySet' object has no attribute 'project_deadline'
报错的代码段是:
Project = models.Project.objects.filter(project_name = request.POST['project_name'])
new_player.project_deadline = Project.project_deadline
想把Project.project_deadline赋值给new_player.project_deadline,报错居然是Project没有对象project_deadline?
吓得我回去看了眼models.py,发现没有拼写错误
我翻到前面看了看自己之前写的一段相似作用的代码
for item in models.Project.objects.filter(project_name = name): #虽然很奇怪但这样写就对了,filter抓不到obj对象,很奇怪...
dict_to_send = {
'project_name':name,
'project_deadline':item.project_deadline,
'project_description':item.project_description
}
return_json = json.dumps(obj=dict_to_send, ensure_ascii=False, cls=DateEncoder)
在其他博主的博客里看到相似内容
大概是用filter()抓出来的对象是一个QuerySet,类似于一个列表,列表中的元素才是我们想要的。
所以在后面取出第一个元素就好了:
Project = models.Project.objects.filter(project_name = request.POST['project_name'])[0]
new_player.project_deadline = Project.project_deadline