On 03/07/12 05:27, Maxime Haineault wrote: > One of the common pitfall I come across way to often with novices is > something like this: > > def getFirstUser(): > return User.objects.all()[0] > > It looks innocuous and often wont raise any exceptions in dev because > you develop and test with data, > so they slip easily in production. > > def getFirstUser(): > return User.objects.all().first() > > If the QuerySet is empty it should just return None instead of raising > an exception.
This very similar to #2659: https://code.djangoproject.com/ticket/2659 except added as a QuerySet method not a shortcut, and .first() wouldn't throw an exception for multiple objects. It was WONTFIXED by Adrian. I'm not keen on this proposal either. There are many small shortcuts you could add, all with slightly different semantics. As mentioned by others, the fastest way to get the first item depends on a lot of things, and also depends on whether you are then going to get the other items. The vast majority of the times that I get the first item of a queryset, I will get other items as well, and for that case .first() would make more work. The idiom I prefer for the case where I know I will only need the first is just this: qs[:1] which returns a queryset with zero or one item. In the context of data passed into a template, it is just as easy to use as the 'item or None' pattern provided by first(): {% if items %} {{ items.0.something }} {% endif %} Luke -- Parenthetical remarks (however relevant) are unnecessary Luke Plant || http://lukeplant.me.uk/ -- You received this message because you are subscribed to the Google Groups "Django developers" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/django-developers?hl=en.
