Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the easiest way to clear a database from the CLI with manage.py in Django?

I am using Django to build a website with MySQL. Now as I am learning so I need to change the Model very often so I want that all tables get cleared and new table get created.

But syncdb doesn't touch existing tables. Is there any better way to handle this problem?

like image 207
Mirage Avatar asked Jun 26 '11 16:06

Mirage


People also ask

How do you clear a database in Python?

Remove a database using Python:Inside a Python Program, obtain a connection object to the MySQL Database server. Using a cursor object obtained through the connection, execute the SQL command DROP DATABASE specifying the name of the database to be deleted.

What does the Django command manage py shell do?

Starts a command line in whatever $SHELL your environment uses. Starts a Django command prompt with your Python environment pre-loaded. Loads a Python command prompt you can use to sync your database schema remotely.

What is manage py commands?

Manage.py in Django is a command-line utility that works similar to the django-admin command. The difference is that it points towards the project's settings.py file. This manage.py utility provides various commands that you must have while working with Django.


1 Answers

If you don't care about data:

Best way would be to drop the database and run syncdb again. Or you can run:

For Django >= 1.5

python manage.py flush 

For Django < 1.5

python manage.py reset appname 

(you can add --no-input to the end of the command for it to skip the interactive prompt.)

If you do care about data:

From the docs:

syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.

If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.

https://docs.djangoproject.com/en/dev/ref/django-admin/

Reference: FAQ - https://docs.djangoproject.com/en/dev/faq/models/#if-i-make-changes-to-a-model-how-do-i-update-the-database

People also recommend South ( http://south.aeracode.org/docs/about.html#key-features ), but I haven't tried it.

like image 70
manojlds Avatar answered Oct 19 '22 03:10

manojlds