Skip to content

Python code snippet – How to check if given primary key exists in django model?

If using the object ---
try:
   obj = model1.objects.get(pk=20)
except DoesNotExist:
   ###do something####
    
Else ----
if model1.objects.filter(pk=20).exists():
   ###do something###
else:
  ###do otherthing###
See also  How to use except statement in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.