How can I delete rows from a database table with some criteria via a migration script? Do I need to manually write it or generate it? How to create the file?
How can I delete rows from a database table with some criteria via a migration script? Do I need to manually write it or generate it? How to create the file?
You need to create an empty migration file:
python manage.py makemigrations <app_label> --empty
open the generated file and add a new operation:
operations = [
migrations.RunPython(delete_some_rows) # name_of_the_function_to_be_called_to_delete_rows
]
define the function in the migration file:
def delete_some_rows(apps, scheme_editor):
model = apps.get_model('app_label', 'model_name')
model.objects.filter(...).delete()
and simply migrate.