【问题标题】:Invalid default value for user_id_id in djangodjango 中 user_id_id 的默认值无效
【发布时间】:2016-06-28 07:09:51
【问题描述】:

我是 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

【问题讨论】:

  • models.ForeignKey 会将“_id”附加到数据库中的真实列名,因此您需要将列名更改为“user”而不是“user_id”。

标签: python mysql django foreign-key-relationship


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    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',))) 
    

    【讨论】:

    • 是 auth_user 表是 django 的用户模型吗?我可以在其中添加自己的字段吗?
    • 您可以extend itreplace it completely。我建议您使用扩展选项,因为它更简单。
    • 谢谢。你为我节省了很多时间。
    猜你喜欢
    • 2021-08-17
    • 2018-01-05
    • 1970-01-01
    • 1970-01-01
    • 2016-12-10
    • 2020-12-01
    • 2014-12-07
    • 2017-06-06
    • 1970-01-01
    相关资源
    最近更新 更多