Managing data in Django typically involves performing CRUD (Create, Read, Update, Delete) operations on your database.
Start the shell by running python manage.py shell
. When you run python manage.py shell
, Django will initialize your project's settings and database configuration, making all your Django apps and models available for use within the shell.
Once we are in the shell, import your model. Below code imports Employee model defined in the models.py
file of the base
app.
from base.models import Employee
Create: To create new records in your database, you instantiate a model object and save it to the database.
employee = Employee(name='pooja', phone='12345', email='pooja@gmail.com')
employee.save()
This creates a new Employee
record with the specified attributes and saves it to the database.
Retrieve (Read):
To retrieve data from the database, you use queryset methods provided by Django's ORM. For example:
employees = Employee.objects.all()
second_employee_phone = Employee.objects.all()[1].phone
#retrieve a single employee by primary key
employee = Employee.objects.get(pk=1)
The first line retrieves all employees from the database. In the second line, we retrieve the phone number of the second employee from the queryset obtained in the first line. We use indexing [1]
to access the second employee (remembering that Python indexing starts from zero).
Update:
To modify existing records in the database, you retrieve the object, update its attributes, and save it back to the database. For example:
employee = Employee.objects.get(pk=1)
employee.name = 'Bambi'
employee.save()
This involves retrieving a single record using get()
, modifying its attributes, and then saving the changes using save()
. This approach is useful when you want to update a single record and perform any custom logic before saving.
Delete:
To remove records from the database, you retrieve the object and call its delete()
method. For example:
employee = Employee.objects.get(id=1)
employee.delete()
# delete multiple records
Employee.objects.filter(name='Singh').delete()
Additional Operations
Filtering:
You can filter querysets to retrieve specific records from the database based on certain conditions:
#employees with a specific name
employees = Employee.objects.filter(name='John')
#employees with phone number greater than a value
employees = Employee.objects.filter(phone__gt=1000)
Ordering:
You can order querysets to retrieve records in a specific order:
#ordered by name in ascending order
employees = Employee.objects.order_by('name')
#ordered by phone number in descending order
employees = Employee.objects.order_by('-phone')
By performing these additional CRUD operations and using queryset methods like filtering, ordering you can effectively manage and manipulate your data in Django applications. You can effectively manage your data in Django, whether it's through Django's admin panel, custom views, or other parts of your application.