DavidL
DavidL

Reputation: 1260

Sorting model fields in set

I'm using this django snippet, which exports data to csv file from the admin. It has these two lines that get field names from the model.

    opts = modeladmin.model._meta
    field_names = set([field.name for field in opts.fields])

However, these field names are not in order. Is there a way to sort by their order of declaration in their model? If not, order a set by alphabetical order?

Upvotes: 1

Views: 261

Answers (1)

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)
field_names.sort()

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.

Upvotes: 2

Related Questions