[Answered ]-Sorting model fields in set


Short answer: No. A set will remove any ordering.

If you want to order by alphabetical order, convert it to a list and call sort() on it.

field_names = list(field_names)

You could check out a few other stack answers to implement an ordered set which will work with the rest of the code (the set & set):

Does Python have an ordered set?

Or replace the code that uses sets with those that use lists:

field_names = [field.name for field in opts.fields]
if fields:
    field_names = filter(lambda field: field in fields, field_names)
elif exclude:
    field_names = filter(lambda field: field not in exclude, field_names)   

I don’t see why a model would ever have multiple fields of the same name, and I don’t see any worthwhile performance gain from using a set for a 10 item set for a periodic admin action, so you might as well remove them.

Leave a comment