jsanchezs
jsanchezs

Reputation: 2070

Conditional with queryset doesn't exist exception in django without using try/except

I need to make an "if" condition with a queryset result as follows :

group_child = Groups.objects.get(subgroup = kwargs["group_id"])
            if group_child is None:
                group = get_object_or_404(Groups, group = kwargs["group_id"])
                group.logic_delete()
                messages.success(request, "Deleted successfull")
            else:
                messages.error(request, "It has elements asociated")

But code never enters the conditional if queryset doesn't exist cause of course, it throws a django exception and also, im not sure if "is None" is valid at all in this scenario.

I know one way to solve it it's using try/except to capture the exception but i wana know if there's another way so i can use the "if" statement as i need.

Thanks in advance

Upvotes: 0

Views: 255

Answers (1)

karthikr
karthikr

Reputation: 99680

.get() raises an exception if the object is not present in the database. You can use a combination of .filter() and .exists() like this:

group_child_qs = Groups.objects.filter(subgroup = kwargs["group_id"])
if group_child_qs.exists():
    group = group_child_qs.first() 
    group.logic_delete()
    messages.success(request, "Deleted successfully")
else:
    messages.error(request, "It has elements associated")

EDIT:

As @knbk mentions, here is a more optimized solution

group = Groups.objects.filter(subgroup = kwargs["group_id"]).first()
if group:
    group.logic_delete()
    messages.success(request, "Deleted successfully")
else:
    messages.error(request, "It has elements associated")

Upvotes: 1

Related Questions