1

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?

juliomalegria
  • 24,229
  • 14
  • 73
  • 89
DavidL
  • 1,260
  • 2
  • 17
  • 35

1 Answers1

2

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.

Community
  • 1
  • 1
Yuji 'Tomita' Tomita
  • 115,817
  • 29
  • 282
  • 245