Reputation: 133
I'm trying to check if an object is exists or not and this is how I do:
try:
control = Card.objects.filter(cc_num = cc_number)[0]
exists = True
except (IndexError):
exists = False
It works but I wonder if there is a more practical way to do?
(The reason I use except(IndexError)
is I'm finding the object with typing [0]
to end of model.objects.filter()
.)
Note: cc_num
is unique.
Upvotes: 2
Views: 8222
Reputation: 678
you can try like this,import this
from django.core.exceptions import ObjectDoesNotExist
try:
controls = Card.objects.get(cc_num == cc_number)
#do something
except ObjectDoesNotExist:
#do something in case not
Upvotes: 0
Reputation: 311
try this: use Card.objects.get() since cc_num is unique, and only one object will be retrieved if it exists
try:
controls = Card.objects.get(cc_num == cc_number)
#do something
except DoesNotExist:
#do something in case not
https://www.codegrepper.com/code-examples/python/check+if+a+value+exist+in+a+model+Django
Upvotes: 2
Reputation: 422
you can do something like this:
if model.objects.filter(email = email).exists():
# at least one object satisfying query exists
else:
# no object satisfying query exists
Check this: https://docs.djangoproject.com/en/stable/ref/models/querysets/#django.db.models.query.QuerySet.exists
Upvotes: 5