Django MySQL error when creating tables

后端 未结 11 1402
感动是毒
感动是毒 2020-12-14 01:02

I am building a django app with a MySQL DB. When I run \'python manage.py migrate\' for the first time, some tables are created well then some errors appear. The error broug

相关标签:
11条回答
  • 2020-12-14 01:34

    Make sure both foreign key and primary key are of the same type.

    Foreign key has to be the same type as the primary key of the foreign table. I had a bigint in the foreign table and django did not know how to create a foreign key that was a bigint automatically.

    Investigated why the migration was failing by running: python manage.py sqlmigrate {app_name} {migration_name}

    Run this in the workbench and you will see the real error behind the failure.

    django.db.utils.IntegrityError: (1215, 'Cannot add foreign key constraint')

    0 讨论(0)
  • 2020-12-14 01:35

    This will works

    python manage.py migrate auth
    python manage.py migrate
    

    The issue because of other migration run before the auth, so this will make sure "authtools"'s migration run first

    0 讨论(0)
  • 2020-12-14 01:35

    i had the same problem with the foreign key 'author_id'.

    The solution was to change the name from

    author = models.ForeignKey(User, related_name='+')
    

    to

    writer = models.ForeignKey(User, related_name='+')
    

    so try to change your name of the field to something different than

    group
    
    0 讨论(0)
  • 2020-12-14 01:40

    Had the same problem, turned out that somehow Django got upgraded to v1.8, promptly downgraded to v1.7 worked.

    0 讨论(0)
  • 2020-12-14 01:41

    I ran into a similar issue while running tests on a Django library against a MySQL database (to avoid Django 2.2 incompatibilities with CentOS 7). This is similar to the problem carton.swing's answer addresses, but takes a different approach to solve the problem.

    A couple of notes about the library I'm testing:

    • The library does not define any models, but the test suite defines models for testing purposes
    • The test suite depends on foreign keys to models it does not define, specifically the auth.User model.

    After looking into an old Django ticket, I noticed this response:

    your problem is that an unmigrated app (authtoken) depends (has a FK to) a migrated app (main). This is a well-known no-no.

    (I couldn't find any other references to this being a "well-known no-no".) Since the test suite defines some models, and also uses auth.User supplied by Django, I guessed that the test runner (pytest, in this case) migrated models defined in the test suite but did not migrate auth.User. To test this, I turned off migrations on my test suite (for pytest-django, this just required adding a --no-migrations flag), which fixed the issue.

    0 讨论(0)
提交回复
热议问题