Does Django ManyToMany field's set() operation clear existing relations?

Viewed 1048

Is there any difference between below 2 cases in Django ORM operation? Will there be any performance gains etc?

obj.manytomanyfield.clear()
obj.manytomanyfield.add(1,2,3,4,5)

and

obj.manytomanyfield.set([1,2,3,4,5])
1 Answers

From the doc, set()-Django doc

This method accepts a clear argument to control how to perform the operation. If False (the default), the elements missing from the new set are removed using remove() and only the new ones are added. If clear=True, the clear() method is called instead and the whole set is added at once.

Which means,

obj.manytomanyfield.clear()
obj.manytomanyfield.add(1,2,3,4,5)

is equal to

obj.manytomanyfield.set([1,2,3,4,5], clear=True)
Related