Assigning unsaved model to a ForeignKey leads to silent failures
|Reported by:||Glenn Maynard||Owned by:||ANUBHAV JOSHI|
|Component:||Database layer (models, ORM)||Version:||master|
|Cc:||anubhav9042@…, altlist@…||Triage Stage:||Accepted|
|Has patch:||yes||Needs documentation:||yes|
|Needs tests:||no||Patch needs improvement:||yes|
Assigning an object to a ForeignKey field without first saving it leads to silent, unobvious failures:
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.)
Change History (48)
comment:12 Changed 4 years ago by
|Patch needs improvement:||set|
|Status:||new → assigned|