diff --git a/django/core/management/commands/inspectdb.py b/django/core/management/commands/inspectdb.py index e45f22c287..5f0e278c61 100644 --- a/django/core/management/commands/inspectdb.py +++ b/django/core/management/commands/inspectdb.py @@ -20,7 +20,7 @@ class Command(NoArgsCommand): def handle_noargs(self, **options): try: for line in self.handle_inspection(options): - print line + self.stdout.write("%s\n" % line) except NotImplementedError: raise CommandError("Database inspection isn't supported for the currently selected database backend.") @@ -66,12 +66,11 @@ class Command(NoArgsCommand): if ' ' in att_name: att_name = att_name.replace(' ', '_') comment_notes.append('Field renamed to remove spaces.') + if '-' in att_name: att_name = att_name.replace('-', '_') comment_notes.append('Field renamed to remove dashes.') - if keyword.iskeyword(att_name): - att_name += '_field' - comment_notes.append('Field renamed because it was a Python reserved word.') + if column_name != att_name: comment_notes.append('Field name made lowercase.') @@ -97,6 +96,10 @@ class Command(NoArgsCommand): extra_params['unique'] = True field_type += '(' + + if keyword.iskeyword(att_name): + att_name += '_field' + comment_notes.append('Field renamed because it was a Python reserved word.') # Don't output 'id = meta.AutoField(primary_key=True)', because # that's assumed if it doesn't exist. diff --git a/tests/regressiontests/inspectdb/__init__.py b/tests/regressiontests/inspectdb/__init__.py new file mode 100644 index 0000000000..8b13789179 --- /dev/null +++ b/tests/regressiontests/inspectdb/__init__.py @@ -0,0 +1 @@ + diff --git a/tests/regressiontests/inspectdb/models.py b/tests/regressiontests/inspectdb/models.py new file mode 100644 index 0000000000..fc2548b441 --- /dev/null +++ b/tests/regressiontests/inspectdb/models.py @@ -0,0 +1,8 @@ +from django.db import models + + +class People(models.Model): + name = models.CharField(max_length=255) + +class Message(models.Model): + from_field = models.ForeignKey(People, db_column='from_id') diff --git a/tests/regressiontests/inspectdb/tests.py b/tests/regressiontests/inspectdb/tests.py new file mode 100644 index 0000000000..a81a97df5e --- /dev/null +++ b/tests/regressiontests/inspectdb/tests.py @@ -0,0 +1,14 @@ +from StringIO import StringIO + +from django.core.management import call_command +from django.test import TestCase + + +class InspectDBTestCase(TestCase): + def test_attribute_name_not_python_keyword(self): + out = StringIO() + call_command('inspectdb', stdout=out) + error_message = "inspectdb generated an attribute name which is a python keyword" + self.assertFalse("from = models.ForeignKey(InspectdbPeople)" in out.getvalue(), msg=error_message) + self.assertTrue("from_field = models.ForeignKey(InspectdbPeople)" in out.getvalue()) + out.close()