Python database integration is an essential part of building systems with Python and Django. One of the most common operations performed on a database is data deletion. This chapter of our complete Python and Django system building course will focus on deleting data using Python.
To work with databases in Python, you need a module called 'sqlite3' that comes pre-installed with Python. SQLite is a lightweight SQL database that does not require a separate server process. This makes SQLite a perfect choice for demonstrating data deletion in Python.
Database Connection
To begin with, you need to connect to the database. Here is an example of how you can do this:
import sqlite3
conn = sqlite3.connect('mydatabase.db')
The above code imports the sqlite3 module and connects to the database 'mydatabase.db'. If the database does not exist, SQLite will create it.
Creating a Table
Before we can delete data, we need a table with some data. Let's create a user table:
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE users(id INTEGER PRIMARY KEY, name TEXT,
email TEXT unique, password TEXT)
''')
conn.commit()
The above code creates a user table with four columns: id, name, email and password. The 'conn.commit()' statement is used to save the changes.
Data Deletion
To delete data from a table, you use the DELETE statement. Here is an example of how you can delete a user with a specific id:
cursor.execute('''
DELETE FROM users WHERE id = ?
''', (id,))
conn.commit()
The above code deletes the user with the specified id. The instruction '?' is a placeholder that is replaced by the value of the tuple (id,). The 'conn.commit()' statement is used again to save the changes.
Deleting Data with Django
With Django, deleting data is even easier. Django is a high-level framework for Python that encourages rapid development and clean, pragmatic design. Here's an example of how you can delete a user with Django:
from django.shortcuts import get_object_or_404
from myapp.models import User
def delete_user(request, id):
user = get_object_or_404(User, pk=id)
user.delete()
The above code first imports the required Django method. It then defines a function that gets the user with the specified id and deletes it.
We hope this chapter has given you a good understanding of how to delete data from a database using Python and Django. In the next chapter, we'll explore how to update data in a database. Stay tuned!