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

Issue:
Related model with primary key causes import exception (regression)
**Describe the bug**
If you have a model which uses an explicit primary key, imports fail

**To Reproduce**
Steps to reproduce the behavior:
1. Create model A with "primary_key=True"
2. Create model B which references (ForeignKey) model A
3. Export data from Model B
4. Import that file into Model B

This produces the failure: `Line number: 1 - 'id'`


**Versions (please complete the following information):**
 - Django Import Export: 4.0.3
 - Python 3.11.8
 - Django 5.0.6

**Expected behavior**
Models import normally. This was working in 3.x

**Screenshots**
![image](https://github.com/django-import-export/django-import-export/assets/56011717/1f6d3b11-2a76-4763-89e0-305b163c9f6e)

**Additional context**
Add any other context about the problem here.



Discussion:

Resolving patch:
diff --git a/import_export/widgets.py b/import_export/widgets.py
--- a/import_export/widgets.py
+++ b/import_export/widgets.py
@@ -541,7 +541,7 @@ def clean(self, value, row=None, **kwargs):
                 lookup_kwargs = self.get_lookup_kwargs(value, row, **kwargs)
                 obj = self.get_queryset(value, row, **kwargs).get(**lookup_kwargs)
                 if self.key_is_id:
-                    return obj.id
+                    return obj.pk
                 return obj
         else:
             return None


Test patch:
diff --git a/tests/core/admin.py b/tests/core/admin.py
--- a/tests/core/admin.py
+++ b/tests/core/admin.py
@@ -9,7 +9,7 @@
 from import_export.resources import ModelResource
 
 from .forms import CustomConfirmImportForm, CustomExportForm, CustomImportForm
-from .models import Author, Book, Category, Child, EBook, UUIDCategory
+from .models import Author, Book, Category, Child, EBook, UUIDBook, UUIDCategory
 
 
 class ChildAdmin(ImportMixin, admin.ModelAdmin):
@@ -42,6 +42,10 @@ class CategoryAdmin(ExportActionModelAdmin):
     pass
 
 
+class UUIDBookAdmin(ImportExportModelAdmin):
+    pass
+
+
 class UUIDCategoryAdmin(ExportActionModelAdmin):
     pass
 
@@ -50,6 +54,11 @@ class AuthorAdmin(ImportMixin, admin.ModelAdmin):
     pass
 
 
+class UUIDBookResource(ModelResource):
+    class Meta:
+        model = UUIDBook
+
+
 class EBookResource(ModelResource):
     published = Field(attribute="published", column_name="published_date")
 
@@ -108,3 +117,4 @@ def get_export_resource_kwargs(self, request, **kwargs):
 admin.site.register(Child, ChildAdmin)
 admin.site.register(EBook, CustomBookAdmin)
 admin.site.register(UUIDCategory, UUIDCategoryAdmin)
+admin.site.register(UUIDBook, UUIDBookAdmin)
diff --git a/tests/core/migrations/0017_namedauthor_uuidbook_author.py b/tests/core/migrations/0017_namedauthor_uuidbook_author.py
new file mode 100644
--- /dev/null
+++ b/tests/core/migrations/0017_namedauthor_uuidbook_author.py
@@ -0,0 +1,32 @@
+# Generated by Django 5.0.4 on 2024-05-24 04:10
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+    dependencies = [
+        ("core", "0016_alter_category_options_alter_uuidcategory_options"),
+    ]
+
+    operations = [
+        migrations.CreateModel(
+            name="NamedAuthor",
+            fields=[
+                (
+                    "name",
+                    models.CharField(max_length=256, primary_key=True, serialize=False),
+                ),
+            ],
+        ),
+        migrations.AddField(
+            model_name="uuidbook",
+            name="author",
+            field=models.ForeignKey(
+                blank=True,
+                null=True,
+                on_delete=django.db.models.deletion.CASCADE,
+                to="core.namedauthor",
+            ),
+        ),
+    ]
diff --git a/tests/core/models.py b/tests/core/models.py
--- a/tests/core/models.py
+++ b/tests/core/models.py
@@ -157,10 +157,19 @@ class Meta:
         proxy = True
 
 
+class NamedAuthor(models.Model):
+    """Class with a named primary key"""
+
+    name = models.CharField(max_length=256, primary_key=True)
+
+
 class UUIDCategory(models.Model):
     catid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
     name = models.CharField(max_length=32)
 
+    def __str__(self):
+        return self.name
+
     class Meta:
         verbose_name_plural = "UUID categories"
 
@@ -170,8 +179,14 @@ class UUIDBook(models.Model):
 
     id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
     name = models.CharField("Book name", max_length=100)
+    author = models.ForeignKey(
+        NamedAuthor, blank=True, null=True, on_delete=models.CASCADE
+    )
     categories = models.ManyToManyField(UUIDCategory, blank=True)
 
+    def __str__(self):
+        return self.name
+
 
 class WithPositiveIntegerFields(models.Model):
     big = models.PositiveBigIntegerField(null=True)
diff --git a/tests/core/tests/test_resources/test_import_export.py b/tests/core/tests/test_resources/test_import_export.py
--- a/tests/core/tests/test_resources/test_import_export.py
+++ b/tests/core/tests/test_resources/test_import_export.py
@@ -2,7 +2,8 @@
 from unittest.mock import patch
 
 import tablib
-from core.models import Author, Book, Category, EBook
+from core.admin import UUIDBookResource
+from core.models import Author, Book, Category, EBook, NamedAuthor, UUIDBook
 from core.tests.resources import AuthorResource, BookResource
 from django.test import TestCase
 
@@ -453,3 +454,24 @@ def test_import_with_column_alias_in_fields_list(self):
         self.resource.import_data(dataset, raise_errors=True)
         self.assertEqual(1, EBook.objects.count())
         self.assertEqual(date(1955, 4, 5), EBook.objects.first().published)
+
+
+class CustomPrimaryKeyRelationImportTest(TestCase):
+    """
+    Test issue 1852.
+    Ensure import works when a relation has a custom primary key.
+    """
+
+    def setUp(self):
+        super().setUp()
+        # The name for this object is the PK
+        self.named_author = NamedAuthor.objects.create(name="Ian Fleming")
+        self.resource = UUIDBookResource()
+
+    def test_custom_column_name_warns_if_not_present(self):
+        dataset = tablib.Dataset(
+            *[("Moonraker", "Ian Fleming")], headers=["name", "author"]
+        )
+        self.assertEqual(0, UUIDBook.objects.count())
+        self.resource.import_data(dataset, raise_errors=True)
+        self.assertEqual(1, UUIDBook.objects.count())