Hi. Thank you for that detail response.

It needs to be clarified that I'm not that worried about exception as it 
could seem :)
It was just an answer to those 2 comments to show that their workarounds 
result in different behaviour than proposed `one`.

`get_or_none` would be useful in my opinion too but still it does not 
exactly the same thing because it would still raise MultipleObjectsReturned.

On the other hand, `one` is:
1) totally safe: None for nothing, same as `get` for 1 object, some random 
row if multiple found
2) have the same DB perfomance as `get`
3) has no overhead for exception (can affect performance in long cycles)


воскресенье, 14 апреля 2019 г., 11:23:17 UTC+3 пользователь Shai Berger 
написал:
>
> Hi, 
>
> I agree that first() should imply ordering, and bemoan the decision, 
> made several years ago, that first() should be the answer to all the 
> people asking for get_or_none(). 
>
> That said, get_or_none()'s definition is trivial: 
>
>         def get_or_none(qs. *args, **kw): 
>                 try: 
>                         return qs.get(*args, **kw) 
>                 except ObjectDoesNotExist: 
>                         return None 
>
> and it's not hard to add it as a method on your own querysets or even 
> monkeypatch it into Django's using a descriptor: 
>
>         class MonkeyPatcher: 
>                 def __init__(self, method): 
>                         self.method = method 
>                 def __get__(self, instance, cls): 
>                         return functools.partial(self.method, instance) 
>
>         QuerySet.get_or_none = MonkeyPatcher(get_or_none) 
>
> (all above untested, Caveat Lector). 
>
> On a side note, you seem to be very worried about the possibility that 
> an exception will be raised. It may be an issue in terms of flow 
> control, but not in terms of overhead, so including code to handle an 
> exception does solve that issue. 
>
> HTH, 
>         Shai. 
>

-- 
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 [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/96a8bb7f-f46f-4124-bf73-b811eb65eaef%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to