16👍
sqlclear management command can be helpful…
Usage: ./manage.py sqlclear [options] <appname appname ...>
Prints the DROP TABLE SQL statements for the given app name(s).
for the postgresql you can do:
./manage.py sqlclear myapp | psql dbname
UPDATE
for apps with migrations and Django 1.7+:
python manage.py migrate <app> zero
13👍
You can do this with the migrate
command which takes two positional arguments:
Updates database schema. Manages both apps with migrations and those without.
positional arguments:
app_label
App label of an application to synchronize the state.
migration_name
Database state will be brought to the state after that
migration. Use the name “zero” to unapply all migrations.
So running a migrate zero followed by a migrate will clear only the data for the given app.
$ python manage.py migrate ${APPNAME} zero
$ python manage.py migrate ${APPNAME}
- [Django]-Override django's model delete method for bulk deletion
- [Django]-Python NameError: name 'include' is not defined
- [Django]-Debugging djcelery's celeryd via pdb
6👍
For later versions of Django try in the Django shell:
from django.apps import apps
my_app = apps.get_app_config('my_app_name')
my_models = my_app.get_models()
for model in my_models:
model.objects.all().delete()
More on the apps
module can be found here.
Of course, you could convert this to a management command yourself using the management infrastructure.
- [Django]-How to see which tests were run during Django's manage.py test command
- [Django]-Django: Error: You don't have permission to access that port
- [Django]-Django: Admin: changing the widget of the field in Admin
0👍
I also needed something to empty only certain apps. I came up with this solution. This worked for mysql. It could be that the code needs to be changed for other databases.
The main idea is not to do the whole ‘flush’. Instead I get only what I want, with a grep from ‘sqlflush’. You can also put everything in one line. For readability I split it up.
BEGIN="BEGIN; SET FOREIGN_KEY_CHECKS = 0;"
TRUNCATE=`./manage.py sqlflush |egrep " \\\`app1_| \\\`app2_"`
END="SET FOREIGN_KEY_CHECKS = 1; COMMIT;"
echo $BEGIN $TRUNCATE $END | ./manage.py dbshell
- [Django]-Reporting yielded results of long-running Celery task
- [Django]-Django and VirtualEnv Development/Deployment Best Practices
- [Django]-PyMongo vs MongoEngine for Django