【发布时间】:2021-09-10 09:28:27
【问题描述】:
如果字段已发行簿中没有数据,我如何抛出 try catch 异常?我没有将任何数据放入已发行的书以进行调试,我只想让它说“未找到数据”或“您没有发行任何书”
这是我的views.py:
def viewissuedbookbystudent(request):
student=models.StudentExtra.objects.filter(user_id=request.user.id)
issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment)
li1=[]
li2=[]
for ib in issuedbook:
books=models.Book.objects.filter(isbn=ib.isbn)
for book in books:
t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author)
li1.append(t)
issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year)
expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year)
#fine calculation
days=(date.today()-ib.issuedate)
print(date.today())
d=days.days
fine=0
if d>15:
day=d-15
fine=day*10
t=(issdate,expdate,fine)
li2.append(t)
context={'li1':li1,'li2':li2}
return render(request,'library/viewissuedbookbystudent.html',context)
我每次运行时都会收到此错误,我知道这是因为已发行簿字段中没有数据:
IndexError at /viewissuedbookbystudent
list index out of range
Request Method: GET
Request URL: http://127.0.0.1:8000/viewissuedbookbystudent
Django Version: 3.2.4
Exception Type: IndexError
Exception Value:
list index out of range
Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py, line 318, in __getitem__
Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.4
Python Path:
['E:\\C drive\\Users\\Admin\\PycharmProjects\\librarymanagement-master',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python39\\site-packages',
'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages'
这是我的模板,如果有帮助的话:
<div class="row">
<div class="col-lg-6" style="padding-right:0px;">
{% if li1%}
<table class="redTable">
<thead>
<tr>
<th>Name</th>
<th>Enrollment</th>
<th>Branch</th>
<th>Book Title</th>
<th>Book Author</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="5">
<div class="links"></div>
</td>
</tr>
</tfoot>
<tbody>
{% for t in li1 %}
<tr>
<td> {{t.0}}</td>
<td> {{t.1}}</td>
<td> {{t.2}}</td>
<td> {{t.3}}</td>
<td> {{t.4}}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<div class="col-lg-6" style="padding-left:0px;">
<table class="redTable">
<thead>
<tr>
<th>Issue Date</th>
<th>Expiry Date</th>
<th>Fine</th>
</tr>
</thead>
<tfoot>
<tr>
<td colspan="5">
<div class="links"></div>
</td>
</tr>
</tfoot>
<tbody>
{% for t in li2 %}
<tr>
<td> {{t.0}}</td>
<td> {{t.1}}</td>
<td> {{t.2}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{%else%}
<h1> No book Issued to you</h1>
{%endif%}
</div>
</div>
class StudentExtra(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
enrollment = models.CharField(max_length=40,verbose_name=_('Student ID'))
course = models.CharField(max_length=40)
#used in issue book
def __str__(self):
return self.user.last_name+'['+str(self.enrollment)+']'
@property
def get_name(self):
return self.user.last_name
@property
def getuserid(self):
return self.user.id
class Category(models.Model):
class Meta:
verbose_name = _('Category')
verbose_name_plural = _('Categories')
ordering = ['id']
name = models.CharField(max_length=255, verbose_name=_('Category'))
def __str__(self):
return self.name
class Book(models.Model):
class Meta:
verbose_name = _('Book')
verbose_name_plural = _('Books')
ordering = ['id']
title=models.CharField(max_length=130)
isbn=models.PositiveIntegerField()
author=models.CharField(max_length=140)
category=models.ForeignKey(Category,on_delete=models.CASCADE)
def __str__(self):
return str(self.title)+"["+str(self.isbn)+']'
def get_expiry():
return datetime.today() + timedelta(days=15)
class IssuedBook(models.Model):
#moved this in forms.py
#enrollment=[(student.enrollment,str(student.get_name)+' ['+str(student.enrollment)+']') for student in StudentExtra.objects.all()]
enrollment=models.CharField(max_length=30)
#isbn=[(str(book.isbn),book.name+' ['+str(book.isbn)+']') for book in Book.objects.all()]
isbn=models.CharField(max_length=30)
issuedate=models.DateField(auto_now=True)
expirydate=models.DateField(default=get_expiry)
def __str__(self):
return self.enrollment
我也有 Traceback: Traceback.png
我可以使用 try catch 修复它吗?如果是,怎么做?
【问题讨论】:
-
与错误没有直接关系,但是你为什么用
.filter()而不是.get()呢?用户 ID 和 ISBN 是唯一的,对吗?对于这些过滤器,您永远不会获得超过一条记录。
标签: python django postgresql django-models django-views