Function LAST_INSERT_ID(); from MySQL returns the ID of the last entry added. Get this value and insert the INSERT into your splicing table.
UPDATE
In general, I was interested and I decided to try to make a small example. Created two tables:
CREATE TABLE table1 ( id integer NOT NULL, -- PrimaryKey name character varying(256) NOT NULL, ); CREATE TABLE table2 ( id integer NOT NULL, -- PrimaryKey name character varying(256) NOT NULL, )
And the table of bundles:
CREATE TABLE table1table2 ( table1_ref integer NOT NULL, table2_ref integer NOT NULL, id integer NOT NULL, -- PrimaryKey )
I connected them with foreign keys and indicated primary ones. We got the following models:
class Table1(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=256) class Meta: db_table = 'table1' class Table1Table2(models.Model): id = models.IntegerField(primary_key=True) table1_ref = models.ForeignKey(Table1, db_column='table1_ref') table2_ref = models.ForeignKey('Table2', db_column='table2_ref') class Meta: db_table = 'table1table2' class Table2(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=256) class Meta: db_table = 'table2'
Next, we write a script that successfully processes and creates the records we need:
from models import Table1, Table2, Table1Table2 t1 = Table1(id=1, name='record #1 in table1') t1.save() t2 = Table2(id=1, name='record #1 in table2') t2.save() t1t2 = Table1Table2(id=1, table1_ref=t1, table2_ref=t2) t1t2.save()
The most interesting thing is that if the tabel1table2 table tabel1table2 not have a primary key, then on the t1t2.save() we get an error, the essence of which is that the table does not have this primary key. At the same time, we don’t need it at all in tabel1table2 , but we had to create it in order for django do what we need (and the component from table1_ref and table2_ref didn’t get through).
From the above, the question to the more experienced comrades follows: is it possible to table1table2 this without a primary key in table1table2 ?