Django

Code

Changeset 7331

Show
Ignore:
Timestamp:
03/20/08 01:56:23 (4 months ago)
Author:
mtredinnick
Message:

Fixed #6445 -- Allow model instances to be used as a default for ForeignKeys?
(via a callable). Also updates the documentation of the "default" attribute to
indicate a callable can be used. Thanks, Philipe Raoult.

Files:

Legend:

Unmodified
Added
Removed
Modified
Copied
Moved
  • django/trunk/django/db/models/fields/related.py

    r7158 r7331  
    549549        return field_objs, params 
    550550 
     551    def get_default(self): 
     552        "Here we check if the default value is an object and return the to_field if so." 
     553        field_default = super(ForeignKey, self).get_default() 
     554        if isinstance(field_default, self.rel.to): 
     555            return getattr(field_default, self.rel.get_related_field().attname) 
     556        return field_default 
     557 
    551558    def get_manipulator_field_objs(self): 
    552559        rel_field = self.rel.get_related_field() 
  • django/trunk/docs/model-api.txt

    r7302 r7331  
    627627~~~~~~~~~~~ 
    628628 
    629 The default value for the field. 
     629The default value for the field. This can be a value or a callable object. If 
     630callable it will be called every time a new object is created. 
    630631 
    631632``editable`` 
  • django/trunk/tests/regressiontests/model_fields/models.py

    r5876 r7331  
     1 
     2from django.db import models 
     3 
     4class Foo(models.Model): 
     5    a = models.CharField(max_length=10) 
     6 
     7def get_foo(): 
     8    return Foo.objects.get(id=1) 
     9 
     10class Bar(models.Model): 
     11    b = models.CharField(max_length=10) 
     12    a = models.ForeignKey(Foo, default=get_foo) 
     13 
     14__test__ = {'API_TESTS':""" 
     15# Create a couple of Places. 
     16>>> f = Foo.objects.create(a='abc') 
     17>>> f.id 
     181 
     19>>> b = Bar(b = "bcd") 
     20>>> b.a 
     21<Foo: Foo object> 
     22>>> b.save() 
     23 
     24"""}