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:

   1. Why does .get() need to perform the extra clone even when there are 
   no arguments? This seems unnecessary to me.
   2. Is there a better way to do what I want to do?

Thanks in advance.

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c67f9206-4b22-45f7-b7e6-1af82d2d94bb%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to