From f283db086469abe91bd1504a339e67274b238899 Mon Sep 17 00:00:00 2001 From: Eric Brelsford Date: Fri, 18 Jul 2014 11:07:45 -0400 Subject: [PATCH 1/2] Don't recalculate attributes --- django_tablib/models.py | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/django_tablib/models.py b/django_tablib/models.py index b21b56f..cb273b5 100644 --- a/django_tablib/models.py +++ b/django_tablib/models.py @@ -80,16 +80,10 @@ def __init__(self, *args, **kwargs): self.fields = {field: Field() for field in included} self.fields.update(deepcopy(self.base_fields)) - fields = [ - field.attribute or name for name, field in self.fields.items() - ] - header_dict = { + self.header_dict = { field.header or name: field.attribute or name for name, field in self.fields.items() } - header_list = header_dict.keys() - - self.attr_list = fields - self.header_dict = header_dict - self.header_list = header_list + self.header_list = self.header_dict.keys() + self.attr_list = [self.header_dict[h] for h in self.header_list] super(ModelDataset, self).__init__(*args, **kwargs) From cfb5f2a5b7477e829b435695bce386be17e5a873 Mon Sep 17 00:00:00 2001 From: Eric Brelsford Date: Fri, 18 Jul 2014 12:14:41 -0400 Subject: [PATCH 2/2] Add field_order option --- django_tablib/models.py | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/django_tablib/models.py b/django_tablib/models.py index cb273b5..72f8dda 100644 --- a/django_tablib/models.py +++ b/django_tablib/models.py @@ -1,4 +1,5 @@ from __future__ import absolute_import +from collections import OrderedDict from copy import deepcopy from .base import BaseDataset @@ -14,6 +15,7 @@ def __init__(self, options=None): self.model = getattr(options, 'model', None) self.queryset = getattr(options, 'queryset', None) self.fields = getattr(options, 'fields', []) + self.field_order = getattr(options, 'field_order', []) self.exclude = getattr(options, 'exclude', []) @@ -80,10 +82,26 @@ def __init__(self, *args, **kwargs): self.fields = {field: Field() for field in included} self.fields.update(deepcopy(self.base_fields)) - self.header_dict = { - field.header or name: field.attribute or name + if self._meta.field_order: + # Add ordered fields + ordered = OrderedDict([ + (field, self.fields[field]) for field in self._meta.field_order + ]) + + # Add fields that exist but were not specified in field_order + unordered = dict([ + (field, self.fields[field]) + for field in self.fields.keys() if field not in ordered + ]) + ordered.update(unordered) + + # Update self.fields to ordered version + self.fields = ordered + + self.header_dict = OrderedDict([ + (field.header or name, field.attribute or name) for name, field in self.fields.items() - } + ]) self.header_list = self.header_dict.keys() self.attr_list = [self.header_dict[h] for h in self.header_list] super(ModelDataset, self).__init__(*args, **kwargs)