Directly creating model instances on ForeignKey field fails
|Reported by:||direx||Owned by:|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, null=True)
Code triggering the bug:
b=Book() b.title="Working title" b.author=Author() b.author.name="Foo Bar" b.author.save() b.save()
What should happen:
- The Author model is being saved first
- The Book model is being saved second, with the created Author instance set as a ForeignKey instance.
What really happens:
- Well, the Author and Book models are saved in the expected order, without any errors, but in the database the author property is NULL. This means that information is silently lost!
Some more words:
If the author attribute had null=False set, an IntegrityError would be raised (author_id may not be NULL), which is better than failing silently, but still bad. The issue with this behavior is that from a normal user's/developer's point of view (without deep knowledge of Django's guts) there is no difference between the following code and the example code above (except that the following code works as expected):
b=Book() b.title="Working title" a=Author() a.name="Foo Bar" a.save() b.author=a b.save()
Of course this can be worked around by end-users by setting b.author_id to b.author.id, but that does not seem logical at all and violates the DRY principle. The real issue probably is the magic triggered by b.author=a. Or Django's ForeignKey lookup is a bit too lazy here...
Change History (6)
comment:5 Changed 3 years ago by
|Component:||Database layer (models, ORM) → Documentation|
|Status:||assigned → new|