Django Update Data
Updating data in Django involves modifying existing records in your database table. This process includes retrieving the specific object you want to update, changing its attributes, and then saving the updated object back to the database.
To open a Python shell, use the command is given below:
python manage.py shell
Now we are in the shell, the result should be something like this:
D:\django_projects\myproject>python manage.py shell Python 3.9.0 (tags/v3.9.0:9cf6752, Oct 5 2020, 15:34:40) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>>
Update Records
Before updating, you need to get the specific record from the database.
>>> from myapp.models import Product >>> a = Product.objects.all()[1]
a will now represent the product at index 1, which is "Orange", but to make sure, let us see if that is correct:
>>> a.product_name
This should give you this result:
'Orange'
Modify and Save the Record
You can update the values of this record as shown below
>>> a.product_name = 'Mango' >>> a.save()
View the Updated Data
To view the updated data use the given command
Product.objects.all().values()
>>> Product.objects.all().values() <QuerySet [ {'id': 1, 'product_name': 'Apple', 'price': 150.0, 'unit': 'Kg'}, {'id': 2, 'product_name': 'Mango', 'price': 120.0, 'unit': 'Kg'}, {'id': 3, 'product_name': 'Strawberry', 'price': 250.0, 'unit': 'Box'}, {'id': 4, 'product_name': 'Water Melon', 'price': 90.0, 'unit': 'Piece'} ]> >>>