Hi all,
I’m wondering what is the best way to handle the logic “if there’s only one entry in the QuerySet, do things with that entry”. What I do currently is
qs = MyModel.objects.filter(...)
try:
obj = qs.get()
except (MyModel.DoesNotExist, MyModel.MultipleObjectsReturned):
for obj in qs: # Something like this
print(obj)
else:
do_something(obj)
This works pretty well, but slightly annoys me because .get() clones and performs an extra fetch on the QuerySet. I guess I have two questions:
- Why does .get() need to perform the extra clone even when there are no arguments? This seems unnecessary to me.
- Is there a better way to do what I want to do?
Thanks in advance.