gpt4 book ai didi

python - Django filter() 查询抛出 DoesNotExist 异常

转载 作者:行者123 更新时间:2023-11-29 13:01:51 30 4
gpt4 key购买 nike

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

最佳答案

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

关于python - Django filter() 查询抛出 DoesNotExist 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27466832/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com