Python django 如何正确测试查询集是否返回结果

标签 python django

我没有接受过非常全面的 Python 培训,有时不知道正确的做事方式。其中之一是测试我的 resultQuery 是否返回结果。我发现自己经常这样做:

    try:
        user = User.objects.get(email=email)
    except DoesNotExist:
        user = User()

我不了解 python,但其他语言的 try catch 应该是针对异常而不是针对正常程序流程的。你会如何用 if else 来做到这一点? 我想我想要类似的东西:

if request.GET.get('email','') is not None:
    email = request.GET['email'])

最佳答案

您的异常示例通常是首选的处理方式。 Wikipedia对此有很好的描述:

Python style calls for the use of exceptions whenever an error condition might arise. Rather than testing for access to a file or resource before actually using it, it is conventional in Python to just go ahead and try to use it, catching the exception if access is rejected.

Exceptions are often used as an alternative to the if-block (...). A commonly-invoked motto is EAFP, or "It is Easier to Ask for Forgiveness than Permission."

异常在 Python 中不一定是昂贵的。再次引用维基百科的例子:

if hasattr(spam, 'eggs'):
    ham = spam.eggs
else:
    handle_error()

...对比:

try:
    ham = spam.eggs
except AttributeError:
    handle_error()

这两个代码示例具有相同的效果,尽管会存在性能差异。当垃圾邮件具有属性 eggs 时,EAFP 示例将运行得更快。当垃圾邮件不具有属性 eggs 时(“异常(exception)”情况),EAFP 示例将运行得更慢。

特别是对于 Django,我会使用异常示例。这是在该框架中做事的标准方式,遵循标准从来都不是坏事:)。

关于Python django 如何正确测试查询集是否返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18676439/

相关文章:

python - Django 帮助 : Resolving NOT NULL constraint failed error with CreateView

c++ - 我应该使用线程编程来混合 2 个音频流吗?

c++ - 使用 Python 在 OpenCV 中解析 XML 或 YML

python - Pandas 中的行满足某些条件,将 dos 条件的值分配给一个单元格

Django celery 和弦不执行

生产中的 Django Celery

python - 如何使用 API 从 Google 文档中提取标题

python - 这个 autokey Python 脚本需要并发吗?

python - Django 读写多个数据库

django-tables2 排除 & 字段不起作用