django中user_id_id的默认值无效

时间:2016-03-13 06:37:16

标签: python mysql django foreign-key-relationship

我是django的新手,我正在创建我的模型但是在尝试将外键添加到另一个模型时遇到了麻烦。这是我的模特:

from django.db import models

class User(models.Model):
    user_id = models.CharField(max_length=10, primary_key=True)
    name = models.CharField(max_length=30)
    surname = models.CharField(max_length=30)
    role = models.CharField(max_length=10)
    address = models.CharField(max_length=50)
    email = models.EmailField(max_length=30)
    password = models.CharField(max_length=20)
    phone = models.IntegerField()
    GPA = models.FloatField(max_length=5)
    Gender = models.CharField(max_length=1)

    def __str__(self):
        return self.user_id


class Login(models.Model):
    user_id = models.ForeignKey(User, on_delete=models.CASCADE,  default='00000')
    email = models.EmailField(max_length=30)
    password = models.CharField(max_length=20)

    def __str__(self):
        return self.email

当我输入makemigrations时,我得到了这个:

You are trying to change the nullable field 'user_id' on login to non-nullable without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows)
 2) Ignore for now, and let me handle existing rows with NULL myself (e.g. because you added a RunPython or RunSQL operation to handle NULL values in a previous data migration)
 3) Quit, and let me add a default in models.py
Select an option:  3

所以我添加了一个默认值,但是当我尝试迁移时出现此错误。我尝试将user_id从User更改为AutoField,因此我不必添加任何默认值,但它仍然给我这个错误。另外,我不知道为什么最后会说user_id_id。任何人都可以帮我解决这个问题吗?

    Running migrations:
      Rendering model states... DONE
      Applying login.0003_login_user_id...Traceback (most recent call last):
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
        return self.cursor.execute(sql, params)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\mysql\base.py", line 112, in execute
        return self.cursor.execute(query, args)
      File "C:\User\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 226, in execute
        self.errorhandler(self, exc, value)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 42, in defaulterrorhandler
        raise errorvalue
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 223, in execute
        res = self._query(query)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 379, in _query
        rowcount = self._do_query(q)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 342, in _do_query
        db.query(q)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 286, in query
        _mysql.connection.query(self, query)
    _mysql_exceptions.OperationalError: (1067, "Invalid default value for 'user_id_id'")

    The above exception was the direct cause of the following exception:

    Traceback (most recent call last):
      File "C:\Program Files (x86)\JetBrains\PyCharm 5.0.4\helpers\pycharm\django_manage.py", line 41, in <module>
        run_module(manage_file, None, '__main__', True)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 182, in run_module
        return _run_module_code(code, init_globals, run_name, mod_spec)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 96, in _run_module_code
        mod_name, mod_spec, pkg_name, script_name)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\runpy.py", line 85, in _run_code
        exec(code, run_globals)
      File "C:/Users/Desktop/Project/TSL/mysite\manage.py", line 10, in <module>
        execute_from_command_line(sys.argv)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 353, in execute_from_command_line
        utility.execute()
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\__init__.py", line 345, in execute
        self.fetch_command(subcommand).run_from_argv(self.argv)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 348, in run_from_argv
        self.execute(*args, **cmd_options)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\base.py", line 399, in execute
        output = self.handle(*args, **options)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\core\management\commands\migrate.py", line 200, in handle
        executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 92, in migrate
        self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 121, in _migrate_all_forwards
        state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\executor.py", line 198, in apply_migration
        state = migration.apply(state, schema_editor)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\migration.py", line 123, in apply
        operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\migrations\operations\fields.py", line 62, in database_forwards
        field,
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\mysql\schema.py", line 50, in add_field
        super(DatabaseSchemaEditor, self).add_field(model, field)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\schema.py", line 396, in add_field
        self.execute(sql, params)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\base\schema.py", line 110, in execute
        cursor.execute(sql, params)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 79, in execute
        return super(CursorDebugWrapper, self).execute(sql, params)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
        return self.cursor.execute(sql, params)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\utils.py", line 95, in __exit__
        six.reraise(dj_exc_type, dj_exc_value, traceback)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\utils\six.py", line 685, in reraise
        raise value.with_traceback(tb)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\utils.py", line 64, in execute
        return self.cursor.execute(sql, params)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\backends\mysql\base.py", line 112, in execute
        return self.cursor.execute(query, args)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 226, in execute
        self.errorhandler(self, exc, value)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 42, in defaulterrorhandler
        raise errorvalue
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 223, in execute
        res = self._query(query)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 379, in _query
        rowcount = self._do_query(q)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\cursors.py", line 342, in _do_query
        db.query(q)
      File "C:\Users\AppData\Local\Programs\Python\Python35-32\lib\site-packages\MySQLdb\connections.py", line 286, in query
        _mysql.connection.query(self, query)
    django.db.utils.OperationalError: (1067, "Invalid default value for 'user_id_id'")

    Process finished with exit code 1

2 个答案:

答案 0 :(得分:0)

首先,如评论中所述,请不要将ForeignKey字段user_id命名为user。这将在db表中创建一个名为user_id的列,并且模型实例的user属性将返回User实例,而其自动生成的属性user_id将返回该用户的id

至于指定ForeignKey的默认值。如果您在模型上执行此操作,请确保提供现有用户。如果您选择在makemigrations期间提供一次性默认设置(如果您选择选项1),请确保提供现有用户的主键。或者,确保数据库中没有现有的Login条记录。

答案 1 :(得分:0)

django会自动为所有模型创建主键,并在内部对其进行管理。

除非您有特殊原因,否则您不希望手动管理或摆弄主键。

现在,您的错误的具体原因是,一旦您将字段类型从CharField更改为AutoField,它就会将字符类型从一个字符更改为一个整数 - 但是您要分配它字符串(字符)的默认值,它会导致数据库出错。

我最好的建议是从头开始。您根本不需要Login模型,django附带authentication built-in及其自己的“用户”模型。

from django.db import models

# Renamed from User to MyUser,
# User is a built-in model that comes with django
# and is used when logging people into the system
# https://docs.djangoproject.com/en/1.9/topics/auth/default/

class MyUser(models.Model):
    name = models.CharField(max_length=30)
    surname = models.CharField(max_length=30)
    role = models.CharField(max_length=10)
    address = models.CharField(max_length=50)
    email = models.EmailField() # email field doesn't need max_length
    password = models.CharField(max_length=20)
    phone = models.CharField(max_length=30) # this should be a CharField
    GPA = models.FloatField()
    gender = models.CharField(max_length=1,
                              choices=(('M', 'Male',),
                                       ('F', 'Female',),
                                       ('X', 'Prefer not to disclose',)))