4

以下のシェル出力で私が見ているものを誰かが説明できますか?

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クエリセットには'business_area_id'属性がないと言っています。これは私を多少混乱させているので、誰かが私をここで正しい軌道に乗せることができますか...

4

4 に答える 4

6

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アソシエイトが 1 人しかいない場合user

biz_area = BusinessArea.objects.get(business_area_manager=user)
biz_are.business_area_id

getそれ以上のオブジェクトがある場合、またはクエリに一致するオブジェクトがない場合に例外が発生することに関するドキュメントを読んでください

于 2013-03-20T15:31:43.350 に答える
0

クエリセットはオブジェクトのコレクションであり (実際にはリストではありbiz_areaませbusiness_area_idんが、プリティ プリントではリストとして表示されます)、business_area_id単一のオブジェクトの属性。

于 2013-03-20T15:17:25.843 に答える
-1

入力すると

type(biz_area)

クエリセットのオブジェクトではなく、リスト型であることがわかります。biz_area 変数内のすべての項目を反復処理して出力する必要があります。

単一のオブジェクトを取得した場合、その business_area_id 属性にアクセスできます。

于 2013-03-20T15:19:56.273 に答える