Repository: django-import-export/django-import-export

Issue:
Export crashes if the column name is used instead of the attribute name
**Describe the bug**

Export will crash if you use a `column_name` in the `fields` list.  v3 works fine if you use either the `column_name` or `attribute`.

**To Reproduce**

Using EBook, change the meta fields list to 

```
fields = ("id", "author_email", "name", "published_date")
```

When exporting, the process will crash with KeyError

**Versions (please complete the following information):**
 - Django Import Export: latest

**Expected behavior**

Either a decent error message, or handle the use of the column name. (import handles the use of the column name)



Discussion:

Resolving patch:
diff --git a/import_export/resources.py b/import_export/resources.py
--- a/import_export/resources.py
+++ b/import_export/resources.py
@@ -1048,8 +1048,18 @@ def export_field(self, field, instance):
         return field.export(instance)
 
     def get_export_fields(self):
-        export_order = self.get_export_order()
-        return [self.fields[f] for f in export_order]
+        export_fields = []
+        for field_name in self.get_export_order():
+            if field_name in self.fields:
+                export_fields.append(self.fields[field_name])
+                continue
+            # issue 1828
+            # allow for fields to be referenced by column_name in `fields` list
+            for field in self.fields.values():
+                if field.column_name == field_name:
+                    export_fields.append(field)
+                    continue
+        return export_fields
 
     def export_resource(self, instance, fields=None):
         export_fields = self.get_export_fields()
@@ -1058,7 +1068,7 @@ def export_resource(self, instance, fields=None):
             return [
                 self.export_field(field, instance)
                 for field in export_fields
-                if field.attribute in fields
+                if field.attribute in fields or field.column_name in fields
             ]
 
         return [self.export_field(field, instance) for field in export_fields]
@@ -1066,7 +1076,11 @@ def export_resource(self, instance, fields=None):
     def get_export_headers(self, fields=None):
         export_fields = self.get_export_fields()
         if isinstance(fields, list) and fields:
-            return [f.column_name for f in export_fields if f.attribute in fields]
+            return [
+                f.column_name
+                for f in export_fields
+                if f.attribute in fields or f.column_name in fields
+            ]
 
         return [force_str(field.column_name) for field in export_fields]
 


Test patch:
diff --git a/tests/core/admin.py b/tests/core/admin.py
--- a/tests/core/admin.py
+++ b/tests/core/admin.py
@@ -65,7 +65,7 @@ class Meta:
         fields = ("id", "author_email", "name", "published")
 
 
-class CustomBookAdmin(ImportExportModelAdmin):
+class CustomBookAdmin(ExportActionModelAdmin, ImportExportModelAdmin):
     """Example usage of custom import / export forms"""
 
     resource_classes = [EBookResource]
diff --git a/tests/core/tests/admin_integration/test_export.py b/tests/core/tests/admin_integration/test_export.py
--- a/tests/core/tests/admin_integration/test_export.py
+++ b/tests/core/tests/admin_integration/test_export.py
@@ -1,11 +1,11 @@
-from datetime import datetime
+from datetime import date, datetime
 from io import BytesIO
 from unittest import mock
 from unittest.mock import MagicMock, patch
 
 import chardet
 import tablib
-from core.admin import BookAdmin, BookResource
+from core.admin import BookAdmin, BookResource, EBookResource
 from core.models import Author, Book, UUIDCategory
 from core.tests.admin_integration.mixins import AdminTestMixin
 from core.tests.utils import ignore_utcnow_deprecation_warning
@@ -465,3 +465,44 @@ def test_selectable_fields_rendered_with_resource_index_attribute(self) -> None:
                 response_content.count(f'resource-index="{index}"'),
                 len(resource_fields),
             )
+
+
+class CustomColumnNameExportTest(AdminTestMixin, TestCase):
+    """Test export ok when column name is defined in fields list (issue 1828)."""
+
+    def setUp(self):
+        super().setUp()
+        EBookResource._meta.fields = ("id", "author_email", "name", "published_date")
+
+    def tearDown(self):
+        super().tearDown()
+        EBookResource._meta.fields = ("id", "author_email", "name", "published")
+
+    def test_export_with_custom_field(self):
+        a = Author.objects.create(id=11, name="Ian Fleming")
+        book = Book.objects.create(
+            name="Moonraker", author=a, published=date(1955, 4, 5)
+        )
+        data = {
+            "format": "0",
+            "author": a.id,
+            "resource": "",
+            "ebookresource_id": True,
+            "ebookresource_author_email": True,
+            "ebookresource_name": True,
+            "ebookresource_published_date": True,
+        }
+        date_str = datetime.now().strftime("%Y-%m-%d")
+        response = self.client.post(self.ebook_export_url, data)
+        self.assertEqual(response.status_code, 200)
+        self.assertTrue(response.has_header("Content-Disposition"))
+        self.assertEqual(response["Content-Type"], "text/csv")
+        self.assertEqual(
+            response["Content-Disposition"],
+            'attachment; filename="EBook-{}.csv"'.format(date_str),
+        )
+        s = (
+            "id,author_email,name,published_date\r\n"
+            f"{book.id},,Moonraker,1955-04-05\r\n"
+        )
+        self.assertEqual(str.encode(s), response.content)
diff --git a/tests/core/tests/admin_integration/test_import.py b/tests/core/tests/admin_integration/test_import.py
--- a/tests/core/tests/admin_integration/test_import.py
+++ b/tests/core/tests/admin_integration/test_import.py
@@ -963,7 +963,7 @@ def test_import_preview_order(self):
 
 
 class CustomColumnNameImportTest(AdminTestMixin, TestCase):
-    """Test preview order displayed correctly (issue 1815)."""
+    """Handle custom column name import (issue 1822)."""
 
     fixtures = ["author"]