检查对象是否存在 [英] Check if an object exists

查看:203
本文介绍了检查对象是否存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要检查 Model.objects.filter(...)打开任何东西,但不需要插入任何东西。我的代码到目前为止:

I need to check if Model.objects.filter(...) turned up anything, but do not need to insert anything. My code so far is:

user_pass = log_in(request.POST)  # form class
if user_pass.is_valid():
    cleaned_info = user_pass.cleaned_data
    user_object = User.objects.filter(email = cleaned_info['username'])


推荐答案

由于过滤器返回 QuerySet ,则可以使用计数查看有多少结果返回。这是假设您实际上不需要结果。

Since filter returns a QuerySet, you can use count to check how many results were returned. This is assuming you don't actually need the results.

num_results = User.objects.filter(email = cleaned_info['username']).count()



在查看文档后,最好调用len on你的过滤器,如果你打算以后使用的结果,因为你只会做一个SQL查询:

After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:


一个count在后台执行SELECT COUNT(*),所以你应该总是使用count(),而不是将所有的记录加载到Python对象中,并在结果上调用len()(除非你需要将对象加载到内存中,这种情况下len()会更快)。

A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).



num_results = len(user_object)

这篇关于检查对象是否存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆