Complete source code for the example in my article on implementing soft deletion in Django.
- Clone repository
- (Optional but recommended) Create a virtual environment,
python -m venv venv
, and activate it,source venv/bin/activate
- Install requirements,
pip install -r requirements.txt
- Create database and run migrations:
python manage.py migrate
- Run the Django shell:
python manage.py shell
Import the relevant models:
from django.contrib.auth.models import User
from tutorialapp.models import Note
Create a user:
john = User.objects.create_user('john', 'lennon@thebeatles.com', 'johnpassword')
Create a couple of notes:
my_note = Note.objects.create(user=john, title="Strawberry Fields", content="Strawberry Fields Forever")
another_note = Note.objects.create(user=john, title="Here Comes The Sun", content="It's All Right")
Soft delete them:
my_note.soft_delete()
And restore them:
my_note.restore()
Fetch undeleted notes:
Note.objects.all()
Fetch all notes, included those that have been soft deleted:
Note.all_objects.all()
Fetch undeleted notes belonging to a user, using Django's reverse relationships:
john.notes.all()