Django filter()查询抛出DoesNotExist异常

时间:2014-12-14 06:11:53

标签: python django postgresql

我正在尝试通过基于相关模型进行过滤来运行filter()查询,并且它会抛出DoesNotExist例外。

CourseMember.objects.filter(user__last_name__icontains='comadena')

我假设过滤不会抛出任何DoesNotExist异常,但如果没有匹配则只返回一个空的查询集。是否有其他get()正在进行,因为我在技术上查询过滤器的相关表格?

另外,奇怪的是,只会针对此特定user__last_name__icontains搜索值抛出错误。它适用于其他值,例如'smith''johnson''frink'等。

型号:

class User(AbstractBaseUser):
  email = models.EmailField(blank=True, null=True, unique=True, max_length=254)
  first_name = models.TextField(blank=True) 
  last_name = models.TextField(blank=True)
  is_superuser = models.BooleanField(default=False)

class Course(models.Model):
  coursenum = models.TextField(blank=True, null=True, db_index=True)
  title = models.TextField(blank=True, null=True)
  school = models.TextField(blank=True, null=True)
  category = models.TextField(blank=True, null=True)

class CourseMember(models.Model):
  create_date = models.DateTimeField(auto_add_now=True)
  course = models.ForeignKey(Course)
  user = models.ForeignKey(User)
  role = models.TextField(blank=True, null=True, db_index=True) 
  section = models.TextField(blank=True, null=True, db_index=True) 

这是我在终端中运行查询时的错误报告:

CourseMember.objects.filter(user__last_name__icontains='comadena')
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 119, in __repr__
    return repr(data)
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/base.py", line 459, in __repr__
    u = six.text_type(self)
  File "/home/bookeducator/go/course/models.py", line 236, in __str__
    return 'CourseMember: %s (%s)' % (self.user.email, self.role)
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/fields/related.py", line 572, in __get__
    rel_obj = qs.get()
  File "/usr/local/lib/python3.4/dist-packages/django/db/models/query.py", line 357, in get
    self.model._meta.object_name)
account.models.DoesNotExist: User matching query does not exist.

1 个答案:

答案 0 :(得分:2)

我发现了这个问题。错误信息指出在调用 str 方法时导致错误,并且我在数据库中发现了导致错误的特定对象。我的系统设置为过滤掉所有没有my_instance.is_active = True的对象。这导致了一个问题,因为过滤器不允许我们返回不再活动的附加用户对象。