L = list # 'list' is a poor variable name, use something else
result = min((n.foo(args) for n in L),
key=lambda x: ClassFred.objects.get(arg1=x))
# if you don't have to use arg1 as a named parameter:
result = min((n.foo(args) for n in L), key=ClassFred.objects.get)
The min function compares the given items and returns the minimum one (of course :P). What isn't obvious at first is you can control what value is used to compare them, this is the 'key' parameter.
>>> L = [-2, -1, 3]
>>> min(L)
-2
>>> min(L, key=abs)
-1
The key function computes the "comparison key", and that is what is used to compare. The default key function is identity, where the comparison key for an item is the item itself.
>>> def identity(x):
... return x
>>> min(L, key=identity)
-2
Another example:
>>> min("0000", "11", "222", "3")
"0000" # lexicographical minimum
>>> min("0000", "11", "222", "3", key=len)
"3"
Your code above is using item.foo(args)
as values, where item comes from your list; but the result of passing that through ClassFred.objects.get(arg1=..)
is used to compare. This means that construct is your key function:
values = (n.foo(args) for n in L) # this is a generator expression
# it is similar to a list comprehension, but doesn't compute or store
# everything immediately
def keyfunc(x):
return ClassFred.objects.get(arg1=x)
result = min(values, key=keyfunc)
My code at the top just puts this together in one statement.