Monday, June 26, 2017

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

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




On 26 June 2017 at 07:32, Tzu-ping Chung <uranusjr@gmail.com> wrote:
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 django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@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.

--
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-users@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/CAFmXjSA0%2B6eRHnDQ9JJQ09%2Br3chtzzcZTn-L4BLQDU1uV0kcoA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.

No comments:

Post a Comment