[Answered ]-Django manytomany add or remove

2👍

When you create a ManyToManyField without specifying an intermediary table (using through) Django generates a table for you. This table will only need the pks of both models, so there’s no need to select anything from the other objects in order to save the new relashionships.

A new row will be created for each of them, possibly using many inserts, but not necessarily many database calls (a single SQL query with multiple insert commands, for instance, is possible). All the info needed for those creations (the pks of your objects) are readily available, so no need for any more database hits than necessary.

Update: seems I was mistaken. Looking at the sources (django/db/models/fields/related.py), I saw that it performs an independent creation for each object:

for obj_id in new_ids:
    self.through._default_manager.using(db).create(**{
        '%s_id' % source_field_name: self._pk_val,
        '%s_id' % target_field_name: obj_id,
    })

Before doing that, it also checks if any of the pks supplied already existed in the database (in order to avoid duplicate entries/uniqueness constraint violations):

vals = self.through._default_manager.using(db).values_list(target_field_name, flat=True)
vals = vals.filter(**{
    source_field_name: self._pk_val,
    '%s__in' % target_field_name: new_ids,
})
new_ids = new_ids - set(vals)

This check is done with a single query though…

0👍

Did you tried to check that by yourself using QuerySet.query attribute?

👤side2k

Leave a comment