I don't like get() and catching exceptions. What I usually do is something like this:
foo_list = Foo.objects.filter(x=x) if (len(foo_list) == 1): foo = foo_list[0] And if I need else, I can assign None or whatever. The advantage in this way is that you don't get an exception, and you deal with all numbers of elements except 1, not only 0 (it can be 2 or 3 for example). And you don't have to catch exceptions for multiple and does-not-exist. Many times I don't need else, I just don't do anything if the number of elements received is not 1. Uri. אורי u...@speedy.net On Tue, Jun 21, 2022 at 10:50 AM Adrian Torres Justo <atorr...@redhat.com> wrote: > A common idiom is also > > ``` > try: > foo = Foo.objects.get(x="foo") > except Foo.DoesNotExist: > foo = None > ``` > > which is pretty pythonic IMO, but I wouldn't be opposed to a keyword-only > argument on `get` that returns `None` if not found > > ``` > foo = Foo.objects.get(x="foo", strict=False) > # or > foo = Foo.objects.get(x="foo", raises=False) > ``` > > As it stands your current proposal isn't much different from filter() then > first(), IMO, the method names change but the amount of chaining is the > same. > On Monday, June 20, 2022 at 9:34:08 PM UTC+2 stev...@gmail.com wrote: > >> It is a common idiom to use `<queryset>.filter(<...>).first()` as a >> replacement for `.get(<...>)` when `None` is wanted instead of an exception >> when no match is found. That works, but wouldn't the intention be more >> clear if that could be written as something like >> >> <queryset>.checked(False).get(<...>) >> > -- > You received this message because you are subscribed to the Google Groups > "Django developers (Contributions to Django itself)" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to django-developers+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/django-developers/eb6a2bc2-b72f-49ff-9e90-12913ad876c9n%40googlegroups.com > <https://groups.google.com/d/msgid/django-developers/eb6a2bc2-b72f-49ff-9e90-12913ad876c9n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group. To unsubscribe from this group and stop receiving emails from it, send an email to django-developers+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/CABD5YeGH7eZqECsCbnC8ifG%2BgOfFW_SY5ug2P-DqYmti4hpmTA%40mail.gmail.com.