Django 3 : Updating objects

Louis SanchezAugust 15th 2021, 4:47

Updating a model instance

Step 1Updating the existing data is very simple. We have already seen what it takes to be able to do so. The following is an example where it modifies the first profile:

from myproject.models import UserProfile
profile = UserProfile.objects.get(id = 1)
profile.name = 'Updateing profile'
profile.save()

Step 2 : The code template

{% extends "base.html" %}
{% block title %}
  {{ action }}
{% endblock %}
{% block h1 %}
  {{ action }}
{% endblock %}
{% block content %}
  {% if all_user_profile|length > 0 %}
  <table>
    <thead>
      <tr>
        <td>ID</td>
        <td>Name</td>
      </tr>
    </thead>
    <tbody>
    {% for profile in all_user_profile %}
      <tr>
        <td>{{ profile.id }}</td>
        <td>{{ profile.name }}</td>
      </tr>
    {% endfor %}
    </tbody>
  </table>
  {% else %}
  <span>No data.</span>
  {% endif %}
{% endblock %}

Step 3 : Now start the development server with the python manage.py runserver command and open http://127.0.0.1:8000/page/ in your browser.

Updating multiple records

Step 3 : To edit multiple records in one shot, you must use the update() method with a queryset object type

from myproject.models import UserProfile
profile = UserProfile.objects.filter(name = "admin").update(name="New Name")