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.

2
  • 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. Commented Apr 9, 2018 at 19:20
  • Possible duplicate of Want to use my existing mysql database with django Commented Apr 9, 2018 at 19:58

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

-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/

3 Comments

I don't know who downvoted this, because it is probably the best answer.
That's the point, to have a full control of everything. Especially database.
Well then... my response is dead on accurate. If the point of an app is to have full control, and you want control as stated in the problem, conflict. Full stop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.