Do something if there’s only one entry in the QuerySet, something else otherwise

9 views
Skip to first unread message

Tzu-ping Chung

unread,
Jun 26, 2017, 1:28:14 PM6/26/17
to Django users
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.

Vinicius Assef

unread,
Jun 26, 2017, 2:49:29 PM6/26/17
to django...@googlegroups.com
Explicit is better than implicit. So, I would stick with:


qs = MyModel.objects.filter(...)

if len(qs) == 0:
    # no record found
elif len(qs) == 1:
    # one record found
else:
    # many records found




--
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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django...@googlegroups.com.
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 all
Reply to author
Forward
0 new messages