The Samurai Principle
Phlip
phlip2005 at gmail.com
Tue Sep 7 12:02:49 EDT 2010
Back to the topic, I tend to do this:
for record in Model.objects.filter(pk=42):
return record
return sentinel
Having lots of short methods helps, because return provides both
control-flow and a result value. But it abuses 'for' to mean 'if'. I
feel _reeeeally_ guilty about that!
But I miss this, from (cough) RoR:
record = Model.find(42) || sentinel
Django should provide this:
record = Model.objects.get(pk=42, _if_does_not_exist=sentinel)
sentinel could be a lambda that concocts a new record (where such a
record should not be created with get_or_create()). That would be
efficient when you don't spend time constructing it just so the happy-
path of .get() can throw it away.
Or sentinel could be None, or a NullObject that efficiently behaves
like a record but provides stubbed-out behaviors.
My committees will be submitting these proposals to the Django
committees shortly... C-:
--
Phlip
More information about the Python-list
mailing list