'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.
Solution 1:[1]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | nzabakira floris |