Python DJANGO错误IndexError / list index超出范围

时间:2017-08-31 04:51:32

标签: python django python-2.7 django-views

我是python的新手。尝试使用django创建一个简单的应用程序。我用这行“ndim = mobjs [0] .ndim”面对索引超出范围异常。任何帮助都将受到高度赞赏

错误

\File "/home/anthra/server_movierecsys/books_recsys_app/views.py", line 66, in home
ndim = mobjs[0].ndim

views.py

def home(request):
context={}
if request.method == 'POST':
    post_data = request.POST
    data = {}
    data = post_data.get('data', None)
    if data:
        return redirect('%s?%s' % (reverse('books_recsys_app.views.home'),
                            urllib.urlencode({'q': data})))
elif request.method == 'GET':
    get_data = request.GET
    data = get_data.get('q',None)
    titles = cache.get('titles')
    if titles==None:
        print ('load data...')
        texts = []
        mobjs = MovieData.objects.all()
        ndim = mobjs[0].ndim
        matr = np.empty([1,ndim])

    else:
        print ('loaded',str(len(titles)))

2 个答案:

答案 0 :(得分:1)

您还可以尝试使用 try:except:语句,但错误除外。您可以编写自己的例外或使用一些biuld:Python Errors and Exceptions

类似的东西:

try:
    mobjs = MovieData.objects.all()
    ndim = mobjs[0].ndim
    matr = np.empty([1,ndim])
except Exception as e: 
    print(e)

希望它有效; P

答案 1 :(得分:0)

试试这个:

    mobjs = MovieData.objects.all().first()
    if mobjs:
        ndim = mobjs[0].ndim
        matr = np.empty([1,ndim])
    else:
        print('there is no MovieData')