attributeRor:“QuerySet”对象没有attribu

2024-05-19 01:08:22 发布

您现在位置:Python中文网/ 问答频道 /正文

有人能解释一下我在下面的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'属性,而对象的漂亮打印列表显示它确实有这样一个属性。有人能把我放在正确的轨道上吗,因为这有点让我困惑。。。


Tags: pytestimportid属性objectmodelsmanager
3条回答

错误的是,biz_area的漂亮打印没有显示它有business_area_id属性,如果它有它就很奇怪了,因为queryset是一个对象集合(在漂亮打印中作为列表可见,尽管它实际上不是列表),而business_area_id是单个对象的属性。

biz_area是Queryset对象,意味着它是对象的集合。 在商务区循环以获取商务区id

for i in biz_area:
  i.business_area_id

biz_areaQuerySet对象。这是一个集合,不是单个对象。

[{'_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列表

有两种处理方法:

过滤器总是返回一个对象集合

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

阅读有关^{}的文档如果有更多对象或0个对象与您的查询匹配,它将引发异常

相关问题 更多 >

    热门问题