Django

Code

Show
Ignore:
Timestamp:
06/04/08 19:39:32 (6 months ago)
Author:
jacob
Message:

Fixed #6886: Tightened up ForeignKey? and OneToOne? field assignment. Specifically:

  • Raise a ValueError? if you try to assign the wrong type of object.
  • Raise a ValueError? if you try to assign None to a field not specified with null=True.
  • Cache the set value at set time instead of just at lookup time.

This is a slightly backwards-incompatible change; see BackwardsIncompatibleChanges for more details.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/tests/regressiontests/many_to_one_regress/models.py

    r5876 r7574  
     1""" 
     2Regression tests for a few FK bugs: #1578, #6886 
     3""" 
     4 
    15from django.db import models 
    26 
     
    2630 
    2731__test__ = {'API_TESTS':""" 
    28 >>> Third.AddManipulator().save(dict(id='3', name='An example', another=None))  
     32>>> Third.objects.create(id='3', name='An example') 
    2933<Third: Third object> 
    3034>>> parent = Parent(name = 'fred') 
    3135>>> parent.save() 
    32 >>> Child.AddManipulator().save(dict(name='bam-bam', parent=parent.id)
     36>>> Child.objects.create(name='bam-bam', parent=parent
    3337<Child: Child object> 
     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 
     51True 
     52 
     53# But if we kill the cache, we get a new object 
     54>>> del c._parent_cache 
     55>>> c.parent is p 
     56False 
     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 
     62True 
     63 
     64# Assigning None fails: Child.parent is null=False 
     65>>> c.parent = None 
     66Traceback (most recent call last): 
     67    ... 
     68ValueError: 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) 
     72Traceback (most recent call last): 
     73    ... 
     74ValueError: Cannot assign "<First: First object>": "Child.parent" must be a "Parent" instance. 
     75 
    3476"""}