54👍
if User.objects.get(pk=id).exists()
This won’t work, so the question is pretty easy to answer: This way is inferior to the ways which do work 🙂
I guess you actually didn’t make a Minimal Complete Verifiable Example and so missed the error when you posted un-verified code.
So instead, I suppose you are asking about the difference between:
-
QuerySet.exists()
when you have a QuerySet (e.g. from a filter operation).For example:
if User.objects.filter(pk=id).exists():
# ... do the things that need that user to exist
-
Model.objects.get(…)
and catching theModel.DoesNotExist
exception type (or, if you want to be more general, the parent typeObjectDoesNotExist
).For example:
try:
user = User.objects.get(pk=id)
except User.DoesNotExist:
# ... handle the case of that user not existing
The difference is:
-
The
QuerySet.exists
method is on a queryset, meaning you ask it about a query (“are there any instances matching this query?”), and you’re not yet attempting to retrieve any specific instance. -
The
DoesNotExist
exception for a model is raised when you actually attempted to retrieve one instance, and it didn’t exist.
Use whichever one correctly expresses your intention.
4👍
You can find more info in docs:
about exists()
,but exists()
works only for QuerySet
Returns True if the QuerySet contains any results, and False if not. This tries to perform the query in the simplest and fastest way possible, but it does execute nearly the same query as a normal QuerySet query.
exists() is useful for searches relating to both object membership in a QuerySet and to the existence of any objects in a QuerySet, particularly in the context of a large QuerySet.
But ObjectDoesNotExist
works only with get()
.
Also you can try another approach:
user = User.objects.filter(id=2)
if user:
# put your logic
pass
- [Django]-How to change ForeignKey display text in the Django Admin?
- [Django]-What is the difference between {% load staticfiles %} and {% load static %}
- [Django]-How to debug gunicorn failure issues? (Worker failed to boot)
2👍
Since we are in Django, we’ll try to catch the error with Django functionality instead of the common way(which is using Exceptions with Python).
id = 1
def a_query(id):
qs = User.objects.filter(pk=id)
if qs.exists():
return qs.first()
return None
In here, the method exists() helps you catching the error(if there’s any).
ref: https://docs.djangoproject.com/en/3.0/ref/models/querysets/#django.db.models.query.QuerySet.exists
- [Django]-Django download a file
- [Django]-Get objects from a many to many field
- [Django]-Meaning of leading underscore in list of tuples used to define choice fields?
1👍
in django model,
if you gonna use model.objects.get()
if it wasn’t exist it raise an error. in that 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
- [Django]-Apache not serving django admin static files
- [Django]-Django – create a unique database constraint for 2 or more fields together
- [Django]-Django-rest-framework how to make model serializer fields required
1👍
For Django version 2.0.6, you can do the following, and it 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 info here: https://docs.djangoproject.com/en/2.1/ref/models/querysets/
- [Django]-Django bulk_create function example
- [Django]-Django REST Framework custom fields validation
- [Django]-Django Admin – save_model method – How to detect if a field has changed?
1👍
It’s my understanding that you’re asking whether to use if statements or try catch on your code. I personally prefer to avoid using try catch, a think it’s an ugly syntax, when I do want to raise an exception, I use a python keyword raise, to me, it makes the code cleaner.
Code example:
user = User.objects.filter(id=2)
if not user:
raise ObjectDoesNotExist
- [Django]-How to access the local Django webserver from outside world
- [Django]-How to check if an element is present in a Django queryset?
- [Django]-Django: Reference to an outer query may only be used in a subquery