Search code examples
python-3.xdjangodjango-modelsdjango-rest-frameworkdjango-orm

django create object and many to many relationship in bulk


Hi I am trying to create multiple objects in bulk with a specific many to many field id specified. Looking at the documentation found this:

>>> e = b.entry_set.create(
...     headline="Hello", body_text="Hi", pub_date=datetime.date(2005, 1, 1)
... )

This works fine and creates the entry object as well as the many-to-many field relation as well.

So modified this to handle bulk_creates:

>>> e = b.entry_set.bulk_create(
...     entry_objects
... )

This does create the entry objects however the many-to-many relation is not getting created in the database.

Am I missing something here?


Solution

  • The .create(…) method [Django-doc] has an override for a RelatedManager, which means that it will set the foreign key, indeed if we look at the source code [GitHub]:

    def create(self, **kwargs):
        self._check_fk_val()
        kwargs[self.field.name] = self.instance
        db = router.db_for_write(self.model, instance=self.instance)
        return super(RelatedManager, self.db_manager(db)).create(**kwargs)

    this is not the case for .bulk_create(…) [Django-doc] which thus falls back on the QuerySet implementation, and thus has no "trigger" to then add the items to the relation.

    You thus basically do this in two calls:

    entry_objects = b.entry_set.bulk_create(entry_objects)
    b.entry_set.add(*entry_objects)