| | 38 | |
|---|
| | 39 | # |
|---|
| | 40 | # Tests of ForeignKey assignment and the related-object cache (see #6886) |
|---|
| | 41 | # |
|---|
| | 42 | >>> p = Parent.objects.create(name="Parent") |
|---|
| | 43 | >>> c = Child.objects.create(name="Child", parent=p) |
|---|
| | 44 | |
|---|
| | 45 | # Look up the object again so that we get a "fresh" object |
|---|
| | 46 | >>> c = Child.objects.get(name="Child") |
|---|
| | 47 | >>> p = c.parent |
|---|
| | 48 | |
|---|
| | 49 | # Accessing the related object again returns the exactly same object |
|---|
| | 50 | >>> c.parent is p |
|---|
| | 51 | True |
|---|
| | 52 | |
|---|
| | 53 | # But if we kill the cache, we get a new object |
|---|
| | 54 | >>> del c._parent_cache |
|---|
| | 55 | >>> c.parent is p |
|---|
| | 56 | False |
|---|
| | 57 | |
|---|
| | 58 | # Assigning a new object results in that object getting cached immediately |
|---|
| | 59 | >>> p2 = Parent.objects.create(name="Parent 2") |
|---|
| | 60 | >>> c.parent = p2 |
|---|
| | 61 | >>> c.parent is p2 |
|---|
| | 62 | True |
|---|
| | 63 | |
|---|
| | 64 | # Assigning None fails: Child.parent is null=False |
|---|
| | 65 | >>> c.parent = None |
|---|
| | 66 | Traceback (most recent call last): |
|---|
| | 67 | ... |
|---|
| | 68 | ValueError: Cannot assign None: "Child.parent" does not allow null values. |
|---|
| | 69 | |
|---|
| | 70 | # You also can't assign an object of the wrong type here |
|---|
| | 71 | >>> c.parent = First(id=1, second=1) |
|---|
| | 72 | Traceback (most recent call last): |
|---|
| | 73 | ... |
|---|
| | 74 | ValueError: Cannot assign "<First: First object>": "Child.parent" must be a "Parent" instance. |
|---|
| | 75 | |
|---|