burak
burak

Reputation: 133

Django Rest Framework how to check an object is exists or not?

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

Answers (3)

Akhil
Akhil

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

nzabakira floris
nzabakira floris

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

Nandan
Nandan

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

Related Questions