Ticket #8892: t8892_2.patch

File t8892_2.patch, 2.7 KB (added by blacklwhite, 13 years ago)

new bugfix in (Reverse-)SingleRelatedObjectDescriptor and tests

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

     
    258258            raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' %
    259259                                (value, instance._meta.object_name,
    260260                                 self.related.get_accessor_name(), self.related.opts.object_name))
     261        # If the related object is not already saved, it has no primary key and
     262        # can not be saved.
     263        elif value is not None and value.pk is None:
     264            raise ValueError('Cannot assign "%r": "%s.%s" must have a primary key.' %
     265                                (value, instance._meta.object_name, self.field.name))
    261266        elif value is not None:
    262267            if instance._state.db is None:
    263268                instance._state.db = router.db_for_write(instance.__class__, instance=value)
     
    330335            raise ValueError('Cannot assign "%r": "%s.%s" must be a "%s" instance.' %
    331336                                (value, instance._meta.object_name,
    332337                                 self.field.name, self.field.rel.to._meta.object_name))
     338        # If the related object is not already saved, it has no primary key and
     339        # can not be saved.
     340        elif value is not None and value.pk is None:
     341            raise ValueError('Cannot assign "%r": "%s.%s" must have a primary key.' %
     342                                (value, instance._meta.object_name, self.field.name))
    333343        elif value is not None:
    334344            if instance._state.db is None:
    335345                instance._state.db = router.db_for_write(instance.__class__, instance=value)
  • tests/modeltests/many_to_one/tests.py

     
    111111        self.assertFalse(hasattr(self.r2.article_set, 'remove'))
    112112        self.assertFalse(hasattr(self.r2.article_set, 'clear'))
    113113
     114        # Assign a reporter without a primary key should raise an error.
     115        a = Article(headline="Carl's biography")
     116        r3 = Reporter(first_name="Carl")
     117        self.assertRaises(ValueError, setattr, a, 'reporter', r3)
     118
     119        # Assign a article without primary key to a reporter should
     120        # raise an error.
     121        self.assertRaises(ValueError, r3.article_set.add, a)
     122
    114123    def test_selects(self):
    115124        new_article = self.r.article_set.create(headline="John's second story",
    116125                                                pub_date=datetime(2005, 7, 29))
Back to Top