Django Check If Object Or a Value Exists Django.How

Author avatar wrote on 06/06/2022

Record checks

Use exists()

if scorm.objects.filter(Header__id=qp.id).exists(): # does not work with get

Use count

sc=scorm.objects.filter(Header__id=qp.id)
if sc.count() > 0:

 

Variables value checks

If in local variables:

if 'myVar' in locals():

 

If in global variables:

if 'myVar' in globals():

 

To check if an object has an attribute:

if hasattr(obj, 'attr_name'):

 

Other ways

try:
    myVar
except NameError:
    myVar = None      # or some other default value.

 

Other way

 myVar = None
 if myVar is not None:

 

Session and request

If in POST request

if 'amount' in request.POST:
    payment_amount = float(request.POST['amount'])

 

If in GET request

if 'amount' in request.GET:
    payment_amount = float(request.GET['amount'])

 

If in session

if 'customer_id' in request.session:
    customer = request.session['customer_id']

 

If in COOKIES

if 'username' in request.COOKIES and 'last_connection' in request.COOKIES:
      username = request.COOKIES['username']