属性错误:'QuerySet'对象没有属性

4

请问有人能解释一下我在下面的shell输出中看到的内容吗:

import test/models.py

biz_area = BusinessArea.objects.filter(business_area_manager=user)

dprint(biz_area)
[{'_state': <django.db.models.base.ModelState object at 0x3726890>,
'business_area_id': Decimal('42'),
'business_area_manager': Decimal('999'),
'business_area_name': u'group 1',
'inactive': u'N'}]

biz_area.business_area_id

Traceback (most recent call last):
File "<<console>console>", line 1, in <<module>module>
AttributeError: 'QuerySet' object has no attribute 'business_area_id'

因此,Python提示说biz_area queryset没有'business_area_id'属性,但对象的漂亮打印列表显示它确实具有这样的属性。有人能否帮助我找到正确的方向,因为这让我感到困惑...


biz_area['business_area_id']是什么意思? - Matthias
@Matthias,那行不通,因为biz_area是一个对象集合。 - dm03514
当然,你是对的。我应该使用我的另一副眼镜来看这个问题... - Matthias
4个回答

6

biz_area 是一个 QuerySet 对象。它是一个集合,而不是单个对象。

[{'_state': <django.db.models.base.ModelState object at 0x3726890>,
'business_area_id': Decimal('42'),
'business_area_manager': Decimal('999'),
'business_area_name': u'group 1',
'inactive': u'N'}]

方括号([])表示一个集合。你可以把它看作Python中的列表。
处理这个问题有几种方法:
filter函数始终会返回一个对象的集合。
biz_areas = BusinessArea.objects.filter(business_area_manager=user)
for biz_area in biz_areas:
  biz_area.business_area_id

如果 BusinessArea 只会有一个关联的 user
biz_area = BusinessArea.objects.get(business_area_manager=user)
biz_are.business_area_id

请阅读有关get的文档,如果有更多对象或0个匹配您查询的对象,则会引发异常。


0
错误,biz_area 的漂亮打印并不显示它有 business_area_id 属性,如果它有的话会很奇怪,因为查询集是对象的集合(在漂亮打印中可见,但实际上不是一个列表),而 business_area_id 是单个对象的属性。

0

biz_area是一个Queryset对象,意味着它是对象的集合。 循环遍历biz_area以获取business_area_id。

for i in biz_area:
  i.business_area_id

-1

如果你输入

type(biz_area)

你会发现这是一个列表类型,而不是来自查询集的对象。你需要遍历 biz_area 变量中的所有项目并将它们打印出来。

如果你检索到单个对象,然后可以像你所做的那样访问它的 business_area_id 属性。


biz_area 是一个 Django.db.models.query.QuerySet。 - ePascoal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接