get the number of MultipleObjectsReturned in exception

try:
    inv = inventory.objects.get(sof_tbl_id=sof_id, active_flag=0)
    someFlag = True
except inventory.DoesNotExist:
    someFlag = False
except inventory.MultipleObjectsReturned as e:
    print(e) # get() returned more than one inventory -- it returned 3!
    inv = inventory.objects.filter(sof_tbl_id=sof_id, active_flag=0).last()
    someFlag = True
finally:
    print("someFlag =", someFlag)

How can I get this value 3 in except ? Using string operations ?

Look inside the code for .get():

If you follow it through, it’s basically a .filter(), a slice to set a limit of 21 (MAX_GET_RESULTS), and then it fetches and checks if there’s one instance, zero, or more than one (MultipleObjectsReturned).

Your code will be simpler if you do the same pattern:

objs = inventory.objects.filter(sof_tbl_id=sof_id, active_flag=0)

if len(objs) == 0:
    someFlag = False
else:
    inv = objs[-1]
    someFlag = True
print("someFlag =", someFlag)

Special handling isn’t even needed for the one object case.

Note this may have poor performance if it’s possible for many objects to match the .fliter(), in which case I’d recommend adding a limit as .get() does.

1 Like