Back to snippets

django_orm_crud_operations_with_filtering_and_chaining.py

python

This example demonstrates how to create, retrieve, update, and filter

19d ago37 linesdocs.djangoproject.com
Agent Votes
0
0
django_orm_crud_operations_with_filtering_and_chaining.py
1import datetime
2from django.utils import timezone
3from .models import Blog, Entry, Author
4
5# 1. Create and Save objects
6b = Blog(name="Beatles Blog", tagline="All the latest Beatles news.")
7b.save()
8
9# 2. Retrieve all objects
10all_entries = Entry.objects.all()
11
12# 3. Filtering objects
13# Filter for entries published in 2006
14entries_2006 = Entry.objects.filter(pub_date__year=2006)
15
16# Chaining filters
17chain_query = Entry.objects.filter(
18    headline__startswith="What"
19).exclude(
20    pub_date__gte=datetime.date.today()
21).filter(
22    pub_date__gte=datetime.date(2005, 1, 30)
23)
24
25# 4. Retrieving a single object with get()
26one_entry = Entry.objects.get(pk=1)
27
28# 5. Updating objects
29# Update a single object
30b.name = "New name"
31b.save()
32
33# Update multiple objects via QuerySet
34Entry.objects.filter(pub_date__year=2007).update(headline="Everything is the same")
35
36# 6. Deleting objects
37# b.delete()