This article mainly introduces how to delete fields and models in Django through databases. Suppose we have created a data model named book. For more information, see
Delete field
Deleting a field from the Model is much easier than adding it. To delete a field, follow these steps:
- Delete the field and restart your web server.
- Run the following command to delete fields from the database:
Alter table books_book drop column num_pages;
Ensure that the operation order is correct. If you delete a field from the database, Django immediately throws an exception.
Delete multiple-to-multiple Association fields
Because many-to-many correlated fields are different from common fields, the delete operation is different.
- Delete ManyToManyField from your model and restart the web server.
- Run the following command to delete an associated table from a database:
Drop table books_book_authors;
Pay attention to the operation sequence as above.
Delete model
Deleting the entire model is easier than deleting a field. To delete a model, follow these steps:
- Delete the model you want to delete from the file, and restart the web server models. py.
- Run the following command to delete a table from the database:
Drop table books_book;
- When you need to delete any dependent tables from the database (that is, any tables that have foreign keys with the books_book table ).
As in the previous section, you must do it in this order.