Ticket #6445: 6645.diff

File 6645.diff, 2.0 KB (added by Philippe Raoult, 17 years ago)

fix + tests + doc

  • django/db/models/fields/related.py

     
    548548            params['choices'] = self.get_choices_default()
    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()
    553560        if self.rel.raw_id_admin and not isinstance(rel_field, AutoField):
  • tests/regressiontests/model_fields/models.py

     
     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"""}
  • docs/model-api.txt

     
    626626``default``
    627627~~~~~~~~~~~
    628628
    629 The default value for the field.
     629The default value for the field. This can be a value or a callable object.
     630If callable it will be used every time a new object is created.
    630631
    631632``editable``
    632633~~~~~~~~~~~~
Back to Top