Flask-SQLAlchemy Many-to-many relationship : How to insert data Flask-SQLAlchemy Many-to-many relationship : How to insert data flask flask

Flask-SQLAlchemy Many-to-many relationship : How to insert data


So:your database is empty.You init db, create table with sqlalchemy... (can't remember the command)

then you do this:

com = Company(company_name='bla')con = Contact(last_name='Blabla', first_name='Jeff', job_position='Resp Marketing',contact_status='Client')con.companies.append(com)db.session.add(con)db.session.commit()

Then you DO this:

#can't remember how to get just one row, is it first instaid of all ? sorrycom_already_created = Company().query.all()[0] con = Contact(last_name='Blabla2', first_name='Jeff2', job_position='Resp Marketing',contact_status='Client')con.companies.append(com_already_created)#orcom_already_created.contacts.append(con)db.session.add(con)db.session.commit()

Your problem was your were creating an element to add to your table Company which already exist (I think you removed PK or unique from "company_name" within "Company" models implementation)

Also:Check for your __repr__, use python3.7 f"string"example :

    def __repr__(self):        return '<Contact {}>'.format(self.last_name, self.first_name,     self.job_position, self.companys, self.contact_status, self.start_date,     self.stop_date)

it should be:

def __repr__(self):    return f'<Contact PK:{self.id}, lst_nm:{self.last_name},     frst_nm:{self.first_name}, jb_pos:{self.job_position>},     cnt_comp:{len(self.companys)}'#(add more if you want but its getting messy)


It sounds like you already have a Company with a company_name of bla in your database. If it already exists, you just need to grab that existing company and then add that object to your Contact. So lets to do that:

# Query the database to find out if we have a company named 'bla'company = Company.query.filter_by(company_name="bla").first()# Did we fail to get a company by the name 'bla'?# If so-- lets create one.if not company:    company = Company(company_name="bla")# Now we're sure to have a company, but not to have a duplicate,# Let's create a new contact, and add the company.contact = Contact(    last_name="Blabla",    first_name="Jeff",    job_position="Resp Marketing",    contact_status="Client",)# Finally lets commit the contact and associated company to the# database.contact.companies.append(company)db.session.add(contact)db.session.commit()


Here is the method I used to add data. This one is simple.

    com = Company(company_name='bla')    db.session.add(com)    con = Contact(last_name='Blabla', first_name='Jeff', job_position='Resp Marketing',     companies= [com] , contact_status='Client')    db.session.add(con)    db.session.commit()