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

Time:02-20

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.

CodePudding user response:

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

CodePudding user response:

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

  • Related