Check if an object exists

前端 未结 6 1908
孤独总比滥情好
孤独总比滥情好 2021-02-02 04:57

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.P         


        
6条回答
  •  一生所求
    2021-02-02 05:33

    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()
    

    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:

    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)
    

提交回复
热议问题