Django exists () compared to DoNotExist

I have some questions about django DoesNotExist exists() and the DoesNotExist exception.

Code example:

 id = 1 # first if User.objects.get(pk=id).exists(): # my logic pass # second try: User.objects.get(pk=id) # my logic pass except User.DoesNotExist: return 0 

I often use the get() method. Which practice is better? Which code is better? First or second?

+12
source share
5 answers

if User.objects.get(pk=id).exists()

This will not work, so the question is fairly easy to answer: this path is inferior to the methods that work :-)

I assume that you did not actually make the Minimal Complete Verifiable Example and therefore missed the error when you posted the unconfirmed code.


So, I suppose you are asking about the difference between:

The difference is that:

  • The QuerySet.exists method is in the query set, that is, you ask it about the query ("are there any instances matching this query?"), And you are not trying to get any particular instance yet.

  • The DoesNotExist exception for the model occurs when you actually tried to get one instance, but it did not exist.

Use one that correctly expresses your intention.

+14
source

You can find additional information in docs : near exists() , but exists() only works for QuerySet

Returns True if the QuerySet contains any results, and False if not. This tries to execute the query in the simplest and fastest way, but it performs almost the same query as a regular QuerySet query.

exists () is useful for searches related to the membership of objects in QuerySet, as well as to the existence of any objects in QuerySet, especially in the context of a large QuerySet.

But ObjectDoesNotExist only works with get() .

You can also try a different approach:

 user = User.objects.filter(id=2) if user: # put your logic pass 
+3
source

in django model, if you are going to use model.objects.get() if it does not exist, an error occurs. in this case you can use DoesNotExist along with except:

 try: val = Model.objects.get(pk=val) # if nothing found it will raise an exception exception: you can trace an exception without mentioning anything on top. (or) exception ObjectDoesNotExist: # it will come here if exception is DoesNotExist 
0
source

Whenever you want to check if there is at least one instance of a class, use the exits method, because it only checks the database for output, and does not retrieve it. So this is a quick .get method trying to get an instance with the given argument.

0
source

For Django version 2.0.6 you can do the following and this will work:

 if Model.objects.filter(my_id=objectid).exists(): myobject = get_object_or_404(Model, my_id=objectid) context = {'myobject': myobject} return render(request, self.template_name, context) 

You can get more information here: https://docs.djangoproject.com/en/2.1/ref/models/querysets/

0
source

Source: https://habr.com/ru/post/1012801/


All Articles