In Django, default CRUD (Create, Read, Update, Delete) operations refer to the built-in capabilities provided by Django to handle these fundamental database actions through its models and views. Here’s an overview:
1. Create
You can use Django’s ORM (Object Relational Mapping) to add new entries to the database.
Example:
obj = MyModel.objects.create(field1="value1", field2="value2")
The save() method can also be used after instantiating a model object:
obj = MyModel(field1="value1", field2="value2")
obj.save()
2. Read
Django provides several ways to retrieve data from the database using the QuerySet API.
Example:
Retrieve all objects: MyModel.objects.all()
Filter objects: MyModel.objects.filter(field1=”value1″)
Get a single object: MyModel.objects.get(id=1)
3. Update
To update an object, retrieve it first, modify its fields, and then call save()
obj = MyModel.objects.get(id=1)
obj.field1 = "new_value"
obj.save()
Bulk updates can be performed with update()
MyModel.objects.filter(field1="value1").update(field2="new_value")
4. Delete
To delete an object, use its delete() method:
obj = MyModel.objects.get(id=1)
obj.delete()
Bulk deletion:
MyModel.objects.filter(field1="value1").delete()
Default CRUD in Django Admin
The Django admin interface provides a default CRUD GUI for managing models:
Create: Add new entries through the admin form.
Read: View existing entries in a list or detail view.
Update: Edit entries using the admin form.
Delete: Remove entries through the admin interface.