﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
10811	Assigning unsaved model to a ForeignKey leads to silent failures	Glenn Maynard	ANUBHAV JOSHI	"Assigning an object to a ForeignKey field without first saving it leads to silent, unobvious failures:

{{{
#!python
class Author(models.Model):
    name = models.CharField(max_length=50)

class Book(models.Model):
    author = models.ForeignKey(Author, null = True)

book = Book.objects.create()
book.author = Author(name=""john"")
book.author.save()
book.save()
}}}

This raises no errors, and saves book with a null author, because the author's PK field was still None at the time it was assigned.

Ideally, this would store the author, pull out the PK at save time rather than assignment time, and raise an error if the author still isn't saved when book.save() is called (and even more ideally, book would hook the author's save and set self.author_id as soon as the author is saved).  Minimally, though, it should raise an error at assignment time to avoid the silent, confusing failure.

(Of course, using create() instead of the object constructor avoids this by saving immediately, but that's not always what's wanted.)
"	Bug	closed	Database layer (models, ORM)	dev	Normal	fixed		anubhav9042@… altlist@…	Accepted	1	1	0	1	0	0
