diff options
| author | Jacob Walls <jacobtylerwalls@gmail.com> | 2025-01-01 18:06:54 -0500 |
|---|---|---|
| committer | Sarah Boyce <42296566+sarahboyce@users.noreply.github.com> | 2025-01-03 16:28:21 +0100 |
| commit | a8e4fd11efc65832e7d9f5582d3868c5c8bd8d88 (patch) | |
| tree | fefd2c626c4dd5f9a16d63672c62df62204df6a5 | |
| parent | ddefc3fed1cf1f0d3fab455babbbc009b76e4196 (diff) | |
Fixed #36052 -- Supported CompositePrimaryKey in inspectdb.
| -rw-r--r-- | django/core/management/commands/inspectdb.py | 16 | ||||
| -rw-r--r-- | tests/inspectdb/tests.py | 5 |
2 files changed, 11 insertions, 10 deletions
diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py index 77605b178f..58594fb66f 100644 --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -106,9 +106,12 @@ class Command(BaseCommand): connection.introspection.get_primary_key_columns( cursor, table_name ) + or [] ) primary_key_column = ( - primary_key_columns[0] if primary_key_columns else None + primary_key_columns[0] + if len(primary_key_columns) == 1 + else None ) unique_columns = [ c["columns"][0] @@ -128,6 +131,11 @@ class Command(BaseCommand): yield "" yield "class %s(models.Model):" % model_name known_models.append(model_name) + + if len(primary_key_columns) > 1: + fields = ", ".join([f"'{col}'" for col in primary_key_columns]) + yield f" pk = models.CompositePrimaryKey({fields})" + used_column_names = [] # Holds column names used in the table so far column_to_field_name = {} # Maps column names to names of model fields used_relations = set() # Holds foreign relations used in the table. @@ -151,12 +159,6 @@ class Command(BaseCommand): # Add primary_key and unique, if necessary. if column_name == primary_key_column: extra_params["primary_key"] = True - if len(primary_key_columns) > 1: - comment_notes.append( - "The composite primary key (%s) found, that is not " - "supported. The first column is selected." - % ", ".join(primary_key_columns) - ) elif column_name in unique_columns: extra_params["unique"] = True diff --git a/tests/inspectdb/tests.py b/tests/inspectdb/tests.py index 1be4efc430..131bd45ce8 100644 --- a/tests/inspectdb/tests.py +++ b/tests/inspectdb/tests.py @@ -655,11 +655,10 @@ class InspectDBTransactionalTests(TransactionTestCase): call_command("inspectdb", table_name, stdout=out) output = out.getvalue() self.assertIn( - f"column_1 = models.{field_type}(primary_key=True) # The composite " - f"primary key (column_1, column_2) found, that is not supported. The " - f"first column is selected.", + "pk = models.CompositePrimaryKey('column_1', 'column_2')", output, ) + self.assertIn(f"column_1 = models.{field_type}()", output) self.assertIn( "column_2 = models.%s()" % connection.features.introspected_field_types["IntegerField"], |
