Ticket #3180: update2.diff

File update2.diff, 4.7 KB (added by Gary Wilson <gary.wilson@…>, 17 years ago)

documentation integrated into the "Saving changes to objects" section instead of creating a new section

  • tests/modeltests/update/models.py

    === added directory 'tests/modeltests/update'
    === added file 'tests/modeltests/update/__init__.py'
    === added file 'tests/modeltests/update/models.py'
     
     1"""
     234. update()
     3
     4update() will update an object's fields with the paramaters passed to it,
     5and then save the object.
     6"""
     7
     8from django.db import models
     9from django.core import validators
     10
     11class User(models.Model):
     12    username = models.CharField(maxlength=30, unique=True,
     13                                validator_list=[validators.isAlphaNumeric])
     14    first_name = models.CharField(maxlength=100)
     15    last_name = models.CharField(maxlength=100)
     16
     17    def __str__(self):
     18        return '%s %s "%s"' % (self.first_name, self.last_name, self.username)
     19
     20    class Meta:
     21        ordering = ('username',)
     22
     23__test__ = {'API_TESTS':"""
     24# Lets create a User.
     25>>> u1 = User.objects.create(username='brave', first_name='Sir', last_name='Robin')
     26
     27# Only one User in the database so far.
     28>>> User.objects.all()
     29[<User: Sir Robin "brave">]
     30
     31# Now we update the user's username and check that it was indeed updated.
     32>>> u1.update(username='notsobrave')
     33>>> u1.username
     34'notsobrave'
     35
     36# We should still only have one User in the database.
     37>>> User.objects.all()
     38[<User: Sir Robin "notsobrave">]
     39
     40# We should be able to grab the User by its new username.
     41>>> u1 = User.objects.get(username='notsobrave')
     42
     43# And we should no longer have a User with username 'brave'.
     44>>> User.objects.filter(username='brave').count()
     450L
     46
     47# Let's create another User.
     48>>> u2 = User.objects.create(username='brave', first_name='Sir', last_name='Lancelot')
     49
     50# Two Users in the database now, and we also have the first User's updated data.
     51>>> User.objects.all()
     52[<User: Sir Lancelot "brave">, <User: Sir Robin "notsobrave">]
     53
     54# We can update more than one field at a time.
     55>>> u1.update(username='pure', last_name='Galahad')
     56
     57# The user did indeed get updated.
     58>>> User.objects.all()
     59[<User: Sir Lancelot "brave">, <User: Sir Galahad "pure">]
     60
     61# If we have a dictionary of fields to change, we can pass that to
     62# update() also.
     63>>> data = {'username': 'knight', 'first_name': 'Knight'}
     64>>> u1.update(**data)
     65>>> u1
     66<User: Knight Galahad "knight">
     67>>> User.objects.all()
     68[<User: Sir Lancelot "brave">, <User: Knight Galahad "knight">]
     69"""}
  • django/db/models/base.py

    === modified file 'django/db/models/base.py'
     
    217217
    218218    save.alters_data = True
    219219
     220    def update(self, **kwargs):
     221        """
     222        Set the object's fields to the new values passed in as keyword
     223        arguments and then save the object.  Fields not specified in the
     224        keyword arguments will not be altered.
     225        """
     226        # Nothing to do if we have no keyword arguments.
     227        if kwargs:
     228            self.__dict__.update(kwargs)
     229            self.save()
     230
     231    update.alters_data = True
     232
    220233    def validate(self):
    221234        """
    222235        First coerces all fields on this instance to their proper Python types.
  • docs/db-api.txt

    === modified file 'docs/db-api.txt'
     
    121121Saving changes to objects
    122122=========================
    123123
    124 To save changes to an object that's already in the database, use ``save()``.
    125 
    126 Given a ``Blog`` instance ``b5`` that has already been saved to the database,
    127 this example changes its name and updates its record in the database::
    128 
    129     b5.name = 'New name'
    130     b5.save()
    131 
    132 This performs an ``UPDATE`` SQL statement behind the scenes. Django doesn't hit
     124``save()``
     125----------
     126
     127Use the ``save()`` method to save an object to the database after making
     128changes to it::
     129
     130    newblog.name = "Brave New World"
     131    newblog.save()
     132
     133This performs an ``UPDATE`` SQL statement behind the scenes (see the
     134`How Django knows to UPDATE vs. INSERT`_ section below).  Django doesn't hit
    133135the database until you explicitly call ``save()``.
    134136
    135137The ``save()`` method has no return value.
    136138
     139``update(**kwargs)``
     140--------------------
     141
     142A convenience method for updating and saving an object all in one step, where
     143(``**kwargs``) are the attributes to update.  Like ``save()``, the
     144``update()`` method has no return value.
     145
     146Using ``update()``, the above code example could be rewritten as::
     147
     148    newblog.update(name="Brave New World")
     149
     150Since ``update()`` calls ``save()`` behind the scenes, Django will hit the
     151database every time ``update()`` is called.
     152
    137153How Django knows to UPDATE vs. INSERT
    138154-------------------------------------
    139155
Back to Top