Django is a powerful Python framework that follows the Model-View-Controller architectural pattern and it is designed to assist in the creation of complex, database-driven websites. The operations Create, Retrieve, Update, and Delete (CRUD) are the four basic functions that models should be able to do, as they are essential to interacting with any database.
CRUD Operations in Django is established by understanding and utilizing Django’s mechanism of templates, URLs, models, and views. Django offers a wide set of features (like HTTP libraries, middleware, authentication, and Django admin) that makes these operations quite flexible and fast.
1. Create: New entries can be made and added to a database via form submission in Django. The input from user is captured through forms and saved as a new object in the database. For example,
\`new\_entry = ModelName(fieldName=value,…)
new\_entry.save()\`
1. Retrieve: Django provides a Queryset API to retrieve information from your database. You can try to get a single record using the `get()` function or multiple records using the `all()`, `filter()`, `exclude()`, etc functions. For example,
\`all\_entries = ModelName.objects.all()
specific\_entry = ModelName.objects.filter(name = ‘xyz’)\`
1. Update: Updating a value in Django involves retrieving the object, changing the value and saving it. Django model’s `save()` function is used after modifying model’s field.
\`entry_to_update = ModelName.objects.get(id=1)
entry_to_update.fieldName = ‘New value‘
entry_to_update.save()\`
1. Delete: To delete a particular record, first, you need to retrieve it and then use the delete() method on the instance. For example,
\`entry_to_delete = ModelName.objects.get(id=1)
entry_to_delete.delete()\`
All of these operations generally happen in views and then the manipulated data is sent to templates via the context dictionary.
Django also provides a high-level Object-Relational Mapping (ORM) which means that you do not need to write any SQL to interact with your database. Instead, Django’s ORM allows you to interact with your database, like you would with SQL. In other words, it’s a way to create, retrieve, update, and delete records in your database using Python.
Sources:
1. Django Documentation (https://docs.djangoproject.com/en/3.2/)
2. RealPython – Django CRUD example with class based views (https://realpython.com/django-redirects/)
3. MDN Web Docs – Django introduction (https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Introduction)
4. Data-flair training – Django CRUD Application (https://data-flair.training/blogs/django-crud-example/)