From 0f22671ecb7e9555300fd2d6cb7bf6dc61735d07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ville=20Skytt=C3=A4?= Date: Sat, 20 Apr 2019 14:26:46 +0300 Subject: [PATCH] Fixed #30388 -- Made inspectdb generate OneToOneFields rather than ForeignKey(unique/primary_key=True). --- django/core/management/commands/inspectdb.py | 12 ++++++++---- tests/inspectdb/tests.py | 4 ++-- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py index 92c2035877..537cd45218 100644 --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -48,7 +48,7 @@ class Command(BaseCommand): yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" - yield "# * Make sure each ForeignKey has `on_delete` set to the desired behavior." + yield "# * Make sure each ForeignKey and OneToOneField has `on_delete` set to the desired behavior" yield ( "# * Remove `managed = False` lines if you wish to allow " "Django to create, modify, and delete the table" @@ -116,14 +116,18 @@ class Command(BaseCommand): extra_params['unique'] = True if is_relation: + if extra_params.pop('unique', False) or extra_params.get('primary_key'): + rel_type = 'OneToOneField' + else: + rel_type = 'ForeignKey' rel_to = ( "self" if relations[column_name][1] == table_name else table2model(relations[column_name][1]) ) if rel_to in known_models: - field_type = 'ForeignKey(%s' % rel_to + field_type = '%s(%s' % (rel_type, rel_to) else: - field_type = "ForeignKey('%s'" % rel_to + field_type = "%s('%s'" % (rel_type, rel_to) else: # Calling `get_field_type` to get the field type string and any # additional parameters and notes. @@ -153,7 +157,7 @@ class Command(BaseCommand): '' if '.' in field_type else 'models.', field_type, ) - if field_type.startswith('ForeignKey('): + if field_type.startswith(('ForeignKey(', 'OneToOneField(')): field_desc += ', models.DO_NOTHING' if extra_params: diff --git a/tests/inspectdb/tests.py b/tests/inspectdb/tests.py index bb5e457739..2dc65eb309 100644 --- a/tests/inspectdb/tests.py +++ b/tests/inspectdb/tests.py @@ -152,11 +152,11 @@ class InspectDBTestCase(TestCase): output, ) self.assertIn( - "people_pk = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, primary_key=True)", + 'people_pk = models.OneToOneField(InspectdbPeople, models.DO_NOTHING, primary_key=True)', output, ) self.assertIn( - "people_unique = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, unique=True)", + 'people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)', output, )