Skip to content
Advertisement

Create one object and bulk-create many related objects

Am new to Django (and Python) and have a problem initializing my model. For every school year created in the database, I want the corresponding days (not exactly 365/366, but > 300) to be created with a default value of 0 (a one-to-many relationship). I learned that I should not try to do this in a constructor, but after the constructor has run (and the object and its attributes have become accessible). So is this a case for using signals or should I override pre- or post-save(). And why? Or is there a third option which I have missed so far?

JavaScript

Advertisement

Answer

Signals tend to be considered an anti-pattern in all but a few cases. You can accomplish the above in a readable fashion by overriding the save function for your year model, and using bulk_create to create a large number of similar objects, giving you something like:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement