Home > Enterprise >  How to check the filter object is returning any data or not in Django
How to check the filter object is returning any data or not in Django

Time:05-22

I have a model named Rooms. Now I want to check if a specific row exists in the model or not by this line of code:

checkroom = Rooms.objects.filter(building_id=building_id, room_no=room_no).first()

If the row doesn't exist, then I want to print some text: How Can I check the condition?

I have used

if checkroom:

this condition to check if it exists. but now I want to check if it doesn't exist separately with an if condition.

CodePudding user response:

I think you can use this :

if not checkroom:
    # Do this...
else:
    # Do that...

CodePudding user response:

You have to use exists query which is faster then retrieve a row.

is_exists_room = Rooms.objects.filter(building_id=building_id, room_no=room_no).exists()

if not is_exists_room:
    print("The room doesn't exist!")
  • Related