011-Django Update Data

Objectives: Django Update Data

Django Update Data

Updating Data in Django

1. Get the Record to Update

Import your model and select the record:

>>> from members.models import Member
>>> x = Member.objects.all()[4]

To check the current value:

>>> x.firstname
'Stale'

Real-life Example:

This is like finding a student in the class list before changing their name in the record book.

2. Update the Record

>>> x.firstname = "Stalikken"
>>> x.save()

3. Verify the Update

>>> Member.objects.all().values()
<QuerySet [{'id': 1, 'firstname': 'Emil', 'lastname': 'Refsnes'},
{'id': 2, 'firstname': 'Tobias', 'lastname': 'Refsnes'},
{'id': 3, 'firstname': 'Linus', 'lastname': 'Refsnes'},
{'id': 4, 'firstname': 'Lene', 'lastname': 'Refsnes'},
{'id': 5, 'firstname': 'Stalikken', 'lastname': 'Refsnes'},
{'id': 6, 'firstname': 'Jane', 'lastname': 'Doe'}]>

Advice:

Always check the record index carefully. QuerySet uses zero-based indexing, so [4] points to the fifth record.

Exercises (5 Q&A)

  1. Question: How do you import the Member model in the Python shell?
    Answer: >> from members.models import Member
  2. Question: How do you select the first member in the QuerySet?
    Answer: >> x = Member.objects.all()[0]
  3. Question: How do you change the last name of a member to "Smith"?
    Answer: >> x.lastname = "Smith"
    >> x.save()
  4. Question: How do you check all members after an update?
    Answer: >> Member.objects.all().values()
  5. Question: What is the correct way to update multiple records in a loop?
    Answer: >>> members = Member.objects.all()
    >>> for x in members:
    ...     x.lastname = "Updated"
    ...     x.save()

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1::