saidul islam nayan
saidul islam nayan

Reputation: 29

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

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.

Upvotes: 1

Views: 2150

Answers (2)

Mukhtor Rasulov
Mukhtor Rasulov

Reputation: 587

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!")

Upvotes: 0

Mostafa Rezaie
Mostafa Rezaie

Reputation: 15

I think you can use this :

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

Upvotes: 1

Related Questions