Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add option for specifying the order fields should appear in #41

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions django_tablib/models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from __future__ import absolute_import
from collections import OrderedDict
from copy import deepcopy

from .base import BaseDataset
Expand All @@ -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', [])


Expand Down Expand Up @@ -80,16 +82,26 @@ 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 = {
field.header or name: field.attribute or name
for name, field in self.fields.items()
}
header_list = header_dict.keys()
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)

self.attr_list = fields
self.header_dict = header_dict
self.header_list = header_list
# 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)