check this id exist in database django

Code to Check if ID Exists in Django Database

from yourapp.models import YourModel

def check_id_exists(id):
    try:
        YourModel.objects.get(pk=id)
        return True
    except YourModel.DoesNotExist:
        return False
  1. Import Necessary Modules: Import the necessary modules, including the model you want to query.

  2. Define the Function: Define a function to check if the ID exists in the database.

  3. Try-Except Block: Use a try-except block to handle the case where the ID does not exist in the database. If the ID is found, the function returns True; if it does not exist, the function returns False.