The Samurai Principle

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Sep 7 13:12:02 EDT 2010


Phlip a écrit :
> Back to the topic, I tend to do this:
> 
>   for record in Model.objects.filter(pk=42):
>      return record
> 
>   return sentinel

WTF alert here...

> 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)

queryset.get can be used with multiple conditions - it's not necessarily 
  restricted to pk lookups. However you name your "_if_does_not_exist" 
kwarg, it will be difficult to garantee that there will never be no 
nameclash with any possible valid model lookup argument...

But if you feel like you found the correct name, you can of course 
monkeypatch queryset !-)



More information about the Python-list mailing list