Fixed #30388 -- Made inspectdb generate OneToOneFields rather than ForeignKey(unique/primary_key=True).

This commit is contained in:
Ville Skyttä 2019-04-20 14:26:46 +03:00 committed by Mariusz Felisiak
parent 5df3301aab
commit 0f22671ecb
2 changed files with 10 additions and 6 deletions

View File

@ -48,7 +48,7 @@ class Command(BaseCommand):
yield "# You'll have to do the following manually to clean this up:" yield "# You'll have to do the following manually to clean this up:"
yield "# * Rearrange models' order" yield "# * Rearrange models' order"
yield "# * Make sure each model has one field with primary_key=True" 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 ( yield (
"# * Remove `managed = False` lines if you wish to allow " "# * Remove `managed = False` lines if you wish to allow "
"Django to create, modify, and delete the table" "Django to create, modify, and delete the table"
@ -116,14 +116,18 @@ class Command(BaseCommand):
extra_params['unique'] = True extra_params['unique'] = True
if is_relation: if is_relation:
if extra_params.pop('unique', False) or extra_params.get('primary_key'):
rel_type = 'OneToOneField'
else:
rel_type = 'ForeignKey'
rel_to = ( rel_to = (
"self" if relations[column_name][1] == table_name "self" if relations[column_name][1] == table_name
else table2model(relations[column_name][1]) else table2model(relations[column_name][1])
) )
if rel_to in known_models: if rel_to in known_models:
field_type = 'ForeignKey(%s' % rel_to field_type = '%s(%s' % (rel_type, rel_to)
else: else:
field_type = "ForeignKey('%s'" % rel_to field_type = "%s('%s'" % (rel_type, rel_to)
else: else:
# Calling `get_field_type` to get the field type string and any # Calling `get_field_type` to get the field type string and any
# additional parameters and notes. # additional parameters and notes.
@ -153,7 +157,7 @@ class Command(BaseCommand):
'' if '.' in field_type else 'models.', '' if '.' in field_type else 'models.',
field_type, field_type,
) )
if field_type.startswith('ForeignKey('): if field_type.startswith(('ForeignKey(', 'OneToOneField(')):
field_desc += ', models.DO_NOTHING' field_desc += ', models.DO_NOTHING'
if extra_params: if extra_params:

View File

@ -152,11 +152,11 @@ class InspectDBTestCase(TestCase):
output, output,
) )
self.assertIn( 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, output,
) )
self.assertIn( self.assertIn(
"people_unique = models.ForeignKey(InspectdbPeople, models.DO_NOTHING, unique=True)", 'people_unique = models.OneToOneField(InspectdbPeople, models.DO_NOTHING)',
output, output,
) )