【问题标题】:AttributeError: 'NoneType' object has no attribute 'ESC'AttributeError:“NoneType”对象没有属性“ESC”
【发布时间】:2020-09-07 19:09:46
【问题描述】:
escs = esc.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')).order_by(
        'id')
edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()

当我尝试print("ESC", edulevel) 时,我收到了这条消息。

ESC None

如何获取esc的id?

这是我的模型:

class StudentsEnrollmentRecord(models.Model):
    Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True)
    Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True)
    ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True)

【问题讨论】:

  • 在 Python 中,变量名应该在 snake_case 中,在你的情况下,student_user 而不是 Student_Users
  • 复制,我现在改一下
  • @ArakkalAbu 先生,它没有解决我的问题
  • 这是一个最佳实践建议
  • 我明白了,先生,我的问题怎么解决?

标签: django django-models django-views


【解决方案1】:

两种可能:

1:您在外键中设置了null=True,这意味着查询集返回的对象在 ecs 外键中为空,因此您可以删除该空约束或在任何之前检查是否为空query_set结果的操作

第二个:这是因为您的查询集没有返回任何对象(您的数据库中没有满足过滤条件的模型对象)

您可以通过以下方式确认:

try:
 edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()
except StudentsEnrollmentRecord.DoesNotExist:
  print("I Did not find anything. Try adding objects first")

可以看到ecs模型的所有对象

#This is only for debugging process to see what objects do you actually have to opt for suitable filters
query_set = esc.objects.all()
print("ecs")
print(query_set)
query_set = StudentsEnrollmentRecord.objects.all()
print("SER")
print(query_set)

更新:

你也可以像这样使用 if 条件

edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()

if(edulevel)
  print(edulevel)

你也可以这样使用计数

edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by(
        'pk').first()

if(edulevel.count()>0)
  print(edulevel)

最后但并非最不重要的一点是,您也可以使用 exists() ,如此处所述 https://stackoverflow.com/a/9089028/11979793

【讨论】:

  • 有什么办法可以解决我不使用 try catch 的问题吗?
  • 我的意思是,如果所选数据的 ID 大于或等于 5,例如,苹果的 ID 为 10,apple >=5
  • 请检查更新的答案,我相信你遇到了问题#1
  • 先生请检查这个问题stackoverflow.com/questions/61931877/…
猜你喜欢
  • 2019-01-01
  • 2021-12-26
  • 2019-07-23
  • 2018-05-13
  • 2017-05-03
  • 2023-03-16
  • 2018-07-14
  • 2013-06-16
  • 2015-06-15
相关资源
最近更新 更多