Fixed #10811 -- Made assigning unsaved objects to FK, O2O, and GFK raise ValueError.

This prevents silent data loss.

Thanks Aymeric Augustin for the initial patch and Loic Bistuer for the review.
This commit is contained in:
Anubhav Joshi 2014-05-19 14:15:55 +05:30 committed by Tim Graham
parent 4f72e5f03a
commit 5643a3b51b
12 changed files with 141 additions and 76 deletions

View file

@ -3,7 +3,7 @@ from __future__ import unicode_literals
from django.db import transaction, IntegrityError
from django.test import TestCase
from .models import (Place, Restaurant, Waiter, ManualPrimaryKey, RelatedModel,
from .models import (Place, Restaurant, Bar, Waiter, ManualPrimaryKey, RelatedModel,
MultiModel)
@ -128,3 +128,20 @@ class OneToOneTests(TestCase):
with self.assertRaises(IntegrityError):
with transaction.atomic():
mm.save()
def test_unsaved_object(self):
"""
#10811 -- Assigning an unsaved object to a OneToOneField
should raise an exception.
"""
place = Place(name='User', address='London')
with self.assertRaisesMessage(ValueError,
'Cannot assign "%r": "%s" instance isn\'t saved in the database.'
% (place, Restaurant.place.field.rel.to._meta.object_name)):
Restaurant.objects.create(place=place, serves_hot_dogs=True, serves_pizza=False)
bar = Bar()
p = Place(name='User', address='London')
with self.assertRaisesMessage(ValueError,
'Cannot assign "%r": "%s" instance isn\'t saved in the database.'
% (bar, p._meta.object_name)):
p.bar = bar