'Django migration to delete rows from database

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1