Skip to content

Commit d4e00f8

Browse files
committed
table.m2m(..., alter=True) option, closes #222
1 parent 0b244d2 commit d4e00f8

File tree

3 files changed

+24
-1
lines changed

3 files changed

+24
-1
lines changed

docs/python-api.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,8 @@ If it cannot find such a table, it will create a new one using the names of the
716716
717717
It it finds multiple candidate tables with foreign keys to both of the specified tables it will raise a ``sqlite_utils.db.NoObviousTable`` exception. You can avoid this error by specifying the correct table using ``m2m_table=``.
718718
719+
The ``.m2m()`` method also takes an optional ``pk=`` argument to specify the primary key that should be used if the table is created, and an optional ``alter=True`` argument to specify that any missing columns of an existing table should be added if they are needed.
720+
719721
.. _python_api_m2m_lookup:
720722
721723
Using m2m and lookup tables together

sqlite_utils/db.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2009,6 +2009,7 @@ def m2m(
20092009
pk=DEFAULT,
20102010
lookup=None,
20112011
m2m_table=None,
2012+
alter=False,
20122013
):
20132014
if isinstance(other_table, str):
20142015
other_table = self.db.table(other_table, pk=pk)
@@ -2045,7 +2046,9 @@ def m2m(
20452046
)
20462047
# Ensure each record exists in other table
20472048
for record in records:
2048-
id = other_table.insert(record, pk=pk, replace=True).last_pk
2049+
id = other_table.insert(
2050+
record, pk=pk, replace=True, alter=alter
2051+
).last_pk
20492052
m2m_table.insert(
20502053
{
20512054
"{}_id".format(other_table.name): id,

tests/test_m2m.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,24 @@ def test_insert_m2m_single(fresh_db):
1414
assert [{"humans_id": 1, "dogs_id": 1}] == list(dogs_humans.rows)
1515

1616

17+
def test_insert_m2m_alter(fresh_db):
18+
dogs = fresh_db["dogs"]
19+
dogs.insert({"id": 1, "name": "Cleo"}, pk="id").m2m(
20+
"humans", {"id": 1, "name": "Natalie D"}, pk="id"
21+
)
22+
dogs.update(1).m2m(
23+
"humans", {"id": 2, "name": "Simon W", "nerd": True}, pk="id", alter=True
24+
)
25+
assert list(fresh_db["humans"].rows) == [
26+
{"id": 1, "name": "Natalie D", "nerd": None},
27+
{"id": 2, "name": "Simon W", "nerd": 1},
28+
]
29+
assert list(fresh_db["dogs_humans"].rows) == [
30+
{"humans_id": 1, "dogs_id": 1},
31+
{"humans_id": 2, "dogs_id": 1},
32+
]
33+
34+
1735
def test_insert_m2m_list(fresh_db):
1836
dogs = fresh_db["dogs"]
1937
dogs.insert({"id": 1, "name": "Cleo"}, pk="id").m2m(

0 commit comments

Comments
 (0)