我一直收到 has no attribute DoesNotExist 错误。
有什么想法吗?
到目前为止我试过:
try:
current_report = Report.objects.get(account_profile=current_profile)
except Report.DoesNotExist:
print("report doesn't exist")
current_report=None
我的调试显示类型对象“Report”没有属性“DoesNotExist” 在 current_report(etc) 行:
我也试过:
from django.core.exceptions import ObjectDoesNotExist
...
except Report.ObjectDoesNotExist:
和
try:
Report.objects.get(account_profile=current_profile)
except Report.DoesNotExist:
print("report doesn't exist")
current_report=None
和
try:
Report.objects.get(account_profile=current_profile)
except ObjectDoesNotExist:
print("report doesn't exist")
current_report=None
为什么类型对象“X”没有属性“DoesNotExist”?我正在使用 Django。
在我的 Models.py 中我有:
class Report(models.Model):
account_profile = models.ForeignKey(Profile)
total_visitors = models.CharField(max_length=200, blank=True, null=True)
last_week_visitors = models.CharField(max_length=200, blank=True, null=True)
new_visitors_this_wk = models.CharField(max_length=200, blank=True, null=True)
new_visitors_last_wk = models.CharField(max_length=200, blank=True, null=True)
bounce_rate = models.CharField(max_length=200, blank=True, null=True)
last_week_bounce_rate = models.CharField(max_length=200, blank=True, null=True)
percent_new_referrals = models.CharField(max_length=100, blank=True, null=True)
last_week_new_referrals = models.CharField(max_length=100, blank=True, null=True)
this_week_pg_load_time = models.CharField(max_length=100, blank=True, null=True)
last_week_pg_load_time = models.CharField(max_length=100, blank=True, null=True)
date_created = models.DateTimeField(default=datetime.now, blank=True)
week_number = models.CharField(max_length=10, blank=True, null=True)
#HTML table for browsers with avg session durations less than 10 seconds
sessions_vs_browser = models.TextField(blank=True, null=True)
sessions_vs_country = models.TextField(blank=True, null=True)
sessions_vs_device = models.TextField(blank=True, null=True)
total_sessions = models.CharField(max_length=100, blank=True, null=True)
keywords = models.ManyToManyField(Keyword)
referrals = models.ManyToManyField(Referral)
pages_speeds = models.ManyToManyField(PageSpeed)
bounces = models.ManyToManyField(BouncePage)
请您参考如下方法:
导入异常,
from django.core.exceptions import ObjectDoesNotExist
捕获它
try:
Report.objects.get(account_profile=current_profile)
except ObjectDoesNotExist:
print("report doesn't exist")
current_report=None
因为 ObjectDoesNotExist 是 Django 特有的异常,您必须导入它才能捕获它。
此外,执行 Model.ObjectDoesNotExist 也不是模型的属性
