mirror of
https://github.com/simonw/sqlite-utils.git
synced 2026-07-24 09:54:31 +02:00
Implemented .m2m(table, lookup=...)
This commit is contained in:
parent
ff2348e71a
commit
ba1211d445
2 changed files with 50 additions and 9 deletions
|
|
@ -1048,21 +1048,31 @@ class Table:
|
|||
self.create_index(column_values.keys(), unique=True)
|
||||
return pk
|
||||
|
||||
def m2m(self, other_table, record_or_list, pk=None):
|
||||
def m2m(self, other_table, record_or_list=None, pk=None, lookup=None):
|
||||
our_id = self.last_pk
|
||||
records = (
|
||||
[record_or_list]
|
||||
if not isinstance(record_or_list, (list, tuple))
|
||||
else record_or_list
|
||||
)
|
||||
if lookup is not None:
|
||||
assert record_or_list is None, "Provide lookup= or record, not both"
|
||||
else:
|
||||
assert record_or_list is not None, "Provide lookup= or record, not both"
|
||||
tables = list(sorted([self.name, other_table]))
|
||||
columns = ["{}_id".format(t) for t in tables]
|
||||
m2m_table = self.db.table(
|
||||
"{}_{}".format(*tables), pk=columns, foreign_keys=columns
|
||||
)
|
||||
# Ensure each record exists in other table
|
||||
for record in records:
|
||||
id = self.db[other_table].upsert(record, pk=pk).last_pk
|
||||
if lookup is None:
|
||||
records = (
|
||||
[record_or_list]
|
||||
if not isinstance(record_or_list, (list, tuple))
|
||||
else record_or_list
|
||||
)
|
||||
# Ensure each record exists in other table
|
||||
for record in records:
|
||||
id = self.db[other_table].upsert(record, pk=pk).last_pk
|
||||
m2m_table.upsert(
|
||||
{"{}_id".format(other_table): id, "{}_id".format(self.name): our_id}
|
||||
)
|
||||
else:
|
||||
id = self.db[other_table].lookup(lookup)
|
||||
m2m_table.upsert(
|
||||
{"{}_id".format(other_table): id, "{}_id".format(self.name): our_id}
|
||||
)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue