1👍
✅
I don’t think the ORM exposes this unless you declare an intermediary model for the relationship. You should be able to do it with a direct SQL call if you don’t need any special behavior like triggering signals. Something like:
field = A._meta.get_field_by_name('b')[0]
tablename = field.m2m_db_table()
column_a_name = field.m2m_column_name()
column_b_name = field.m2m_reverse_name()
from django.db import connection, transaction
cursor = connection.cursor()
for (id, related_ids) in related_map.iteritems():
for related_id in related_ids:
cursor.execute("insert into %s (%s, %s) values (%s, %s)", (tablename, column_a_name, column_b_name, id, related_id))
transaction.commit_unless_managed()
https://docs.djangoproject.com/en/1.5/topics/db/sql/#executing-custom-sql-directly has the full docs and discussion of transaction control options.
Those field lookups are not part of the documented API, so there’s probably a risk of them changing in future versions.
Source:stackexchange.com