【发布时间】:2017-12-22 19:23:51
【问题描述】:
让我们考虑一下我正在尝试查找主键为 20 的用户是否存在?我可以通过两种方式做到这一点。
第一个:
try:
user = User.objects.get(pk=20)
except User.DoesNotExist:
handle_non_existent_user()
另一种方式可能是:
users = User.objects.filter(pk=20)
if not users.exists():
handle_non_existent_user()
检查存在的更好方法是什么?
这可能与此有关:What is the best way to check if data is present in django? 但是,由于指定的示例没有模型查询集的参考,人们更喜欢第一种方法。
也在以下问题的答案中:what is the right way to validate if an object exists in a django view without returning 404? 它主要是基于,因为我们没有得到相关对象的引用。
【问题讨论】:
-
exists()
存在仅出于一个原因。请使用它。在某些情况下,例如当您计划评估查询集时,请使用bool(queryset)
而不是exists()
(from the docs)
标签: python mysql django django-models django-views