【问题标题】:Django filter() query throwing DoesNotExist exceptionDjango filter() 查询抛出 DoesNotExist 异常
【发布时间】:2014-12-14 06:11:52
【问题描述】:

我正在尝试通过基于相关模型的过滤来运行 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.

【问题讨论】:

  • 你能提供你的相关模型定义和你得到的完整回溯吗?谢谢。
  • 希望编辑有所帮助。

标签: python django postgresql


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-02
    • 2020-03-12
    • 2012-06-21
    • 2011-09-03
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 1970-01-01
    相关资源
    最近更新 更多