How to CRUD with Django
Django has a powerful ORM that makes working with a database very easy. For the example below we will use the following model (or database table):
from django.db import models
class Todo(models.Model):
text = models.TextField()
is_done = models.BooleanField(default=False)
Query data
To get a single item given with the primary key you can use the get
function:
Todo.objects.get(id=1)
To get multiple records you can use the filter
function:
Todo.objects.filter(is_done=True)
Create data
To create a record you can simply do:
Todo.objects.create(
text="Groceries",
is_done=False # This field can be also omitted as it is optional
)
If you want to create multiple records at once you can use the bulk_create
method:
Todo.objects.bulk_create([
Todo(text="Clean dishes",
Todo(text="Clean house")
])
Update data
To update an existing record you can simply modify its values and then use save
:
todo.text = "Clean dishes with the dishwasher"
todo.save()
If you want to update multiple records at once you can use the update
function:
Todo.objects.all().update(is_done=True)
Delete data
To delete records you can use the delete
function:
todo.delete()
You can apply it also to multiple records at one:
Todo.objects.all().delete()