db.models.fields.related.RelatedManager.add()

add(*objs, bulk=True)

Adds the specified model objects to the related object set.

Example:

>>> b = Blog.objects.get(id=1)
>>> e = Entry.objects.get(id=234)
>>> b.entry_set.add(e) # Associates Entry e with Blog b.

In the example above, in the case of a ForeignKey relationship, QuerySet.update() is used to perform the update. This requires the objects to already be saved.

You can use the bulk=False argument to instead have the related manager perform the update by calling e.save().

Using add() with a many-to-many relationship, however, will not call any save() methods, but rather create the relationships using QuerySet.bulk_create(). If you need to execute some custom logic when a relationship is created, listen to the m2m_changed signal.

Changed in Django 1.9:

The bulk parameter was added. In older versions, foreign key updates were always done using save(). Use bulk=False if you require the old behavior.

doc_Django
2016-10-09 18:35:34
Comments
Leave a Comment

Please login to continue.