我正在尝试编写一个简单的算法来获得django mptt模型的“等级”。 'rank'是指后代级别的数量......类似于MPTTModel.get_level(),但从叶到根计数。
我的方法如下:
views.py
def index(request):
nodes = Node.objects.all()
nodesets = []
for i in nodes:
figure_rank(i, i)
if i.count >= 3:
nodeset = Node_set(node=i, name=i.name)
nodeset.save() # This is where the error is caught
nodesets.append(dataset)
return render(request, 'associate/index.html', {'nodesets':nodesets})
def figure_rank(over, under):
if under.get_children()[0]:
r = under.get_children()[0]
over.count += 1
figure_rank(over, r)
else:
return over.count
对于排名> gt = 3的节点,我想创建一个Node_set,并在它们全部给定排名后返回一组节点。
我收到以下错误:
Environment:
Request Method: GET
Request URL: http://127.0.0.1:8000/associate/
Django Version: 1.6.2
Python Version: 2.7.5
Installed Applications:
('django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'associate',
'images_app',
'mptt')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware')
Traceback:
File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in get_response
114. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\djangoprojects\images\associate\views.py" in index
9. figure_rank(i, i)
File "C:\djangoprojects\images\associate\views.py" in figure_rank
23. figure_rank(over, r)
File "C:\djangoprojects\images\associate\views.py" in figure_rank
23. figure_rank(over, r)
File "C:\djangoprojects\images\associate\views.py" in figure_rank
20. if under.get_children()[0]:
File "C:\Python27\lib\site-packages\django\db\models\query.py" in __getitem__
132. return list(qs)[0]
Exception Type: IndexError at /associate/
Exception Value: list index out of range
我在这里做错了什么?
答案 0 :(得分:1)
您需要正确检查是否没有孩子。在figure_rank
中,under.get_children()
返回一个空列表,然后您尝试访问第一个元素。首先检查列表是否为空。
def figure_rank(over, under):
children = under.get_children()
if chilren: # check if children is nonempty before accessing the first element
r = children[0]
over.count += 1
figure_rank(over, r)
else:
return over.count