1

I have an application in Django 2.0 and as a database engine I use MySQL. I have a problem because the database was previously created and already has records, my idea is to use this same database for the application I am creating.

Use the command

python manage.py inspectdb > models.py

To create the models.py file which will be cleaned as indicated by the models.py file that was generated.

#This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.

After this I proceed to execute:

python manage.py migrate
python manage.py makemigrations
python manage.py migrate

But it generates the following error:

(1050, "Table 'XXXXXXX' already exists")

Obviously it tells me that the table already exists, but how do I not generate this error and continue administering the tables from Django.

jhon1946
  • 183
  • 10
  • The question is: Do you want to manage your database with Django or not? If not, simply use `managed = False` in the `Meta` class of the object and don't mage migrations. If you want Django to "take over" the management, it is possible, but a little tricky. – masterfloda Apr 09 '18 at 19:20
  • Possible duplicate of [Want to use my existing mysql database with django](https://stackoverflow.com/questions/21683095/want-to-use-my-existing-mysql-database-with-django) – toonarmycaptain Apr 09 '18 at 19:58

2 Answers2

0

You need to run --fake-initial or --fake. See more at Django migrations. Be careful because running inspectdb doesn't solve all your problems. You need to fix the things inside models.py manually and migrate again.

Goran
  • 6,644
  • 11
  • 34
  • 54
-1

One of the things (and the main reason I do not use Django) is it likes to take control of everything. The fact that it controls the database means that if you don't start strictly in Django, you are doing it wrong.

However there is a work around:

https://docs.djangoproject.com/en/2.0/howto/legacy-databases/

eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20