[Fixed]-Conditional with queryset doesn't exist exception in django without using try/except

1๐Ÿ‘

โœ…

.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")
๐Ÿ‘คkarthikr

Leave a comment