| | 1 | """ |
| | 2 | 34. update() |
| | 3 | |
| | 4 | update() will update an object's fields with the paramaters passed to it, |
| | 5 | and then save the object. |
| | 6 | """ |
| | 7 | |
| | 8 | from django.db import models |
| | 9 | from django.core import validators |
| | 10 | |
| | 11 | class 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() |
| | 45 | 0L |
| | 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 | """} |