2
Tests for the update() queryset method that allows in-place, multi-object
6
from django.db import models
8
class DataPoint(models.Model):
9
name = models.CharField(max_length=20)
10
value = models.CharField(max_length=20)
11
another_value = models.CharField(max_length=20, blank=True)
13
def __unicode__(self):
14
return unicode(self.name)
16
class RelatedPoint(models.Model):
17
name = models.CharField(max_length=20)
18
data = models.ForeignKey(DataPoint)
20
def __unicode__(self):
21
return unicode(self.name)
24
__test__ = {'API_TESTS': """
25
>>> DataPoint(name="d0", value="apple").save()
26
>>> DataPoint(name="d2", value="banana").save()
27
>>> d3 = DataPoint.objects.create(name="d3", value="banana")
28
>>> RelatedPoint(name="r1", data=d3).save()
30
Objects are updated by first filtering the candidates into a queryset and then
31
calling the update() method. It executes immediately and returns nothing.
33
>>> DataPoint.objects.filter(value="apple").update(name="d1")
35
>>> DataPoint.objects.filter(value="apple")
38
We can update multiple objects at once.
40
>>> DataPoint.objects.filter(value="banana").update(value="pineapple")
42
>>> DataPoint.objects.get(name="d2").value
45
Foreign key fields can also be updated, although you can only update the object
46
referred to, not anything inside the related object.
48
>>> d = DataPoint.objects.get(name="d1")
49
>>> RelatedPoint.objects.filter(name="r1").update(data=d)
51
>>> RelatedPoint.objects.filter(data__name="d1")
54
Multiple fields can be updated at once
56
>>> DataPoint.objects.filter(value="pineapple").update(value="fruit", another_value="peaches")
58
>>> d = DataPoint.objects.get(name="d2")
59
>>> d.value, d.another_value
60
(u'fruit', u'peaches')
62
In the rare case you want to update every instance of a model, update() is also
65
>>> DataPoint.objects.update(value='thing')
67
>>> DataPoint.objects.values('value').distinct()
70
We do not support update on already sliced query sets.
72
>>> DataPoint.objects.all()[:2].update(another_value='another thing')
73
Traceback (most recent call last):
75
AssertionError: Cannot update a query once a slice has been taken.