I have created a many-to-many relationship in my Flask-Sqlalchemy models. However it seems that I don't well understand how to fill my database. Could you please tell me how I suppose to write my code to fill my database correctly?
Here are my models:
company_contact = db.Table('company_contact', db.Model.metadata, db.Column('company_id', Integer, ForeignKey('company.id')), db.Column('contact_id', Integer, ForeignKey('contact.id')) ) class Company(db.Model): __tablename__ = 'company' id = db.Column(db.Integer, primary_key=True, autoincrement=True) contacts = db.relationship('Contact', secondary=company_contact, back_populates="companies") company_name = db.Column(db.String(100)) def __repr__(self): return '<Company {}{}>'.format(self.contacts, self.company_name) class Contact(db.Model): __tablename__ = 'contact' id = db.Column(db.Integer, primary_key=True, autoincrement=True) last_name = db.Column(db.String(255)) first_name = db.Column(db.String(255)) job_position = db.Column(db.String(255)) companies = db.relationship('Company', secondary=company_contact, back_populates="contacts") contact_status = db.Column(db.Enum('Client', 'Prospect', 'Churner', 'Prestataire', 'Reperage', name='contact_status')) start_date = db.Column(db.DateTime, server_default=db.func.now()) stop_date = db.Column(db.DateTime, default=None) 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) What I'm trying to do, is to add two Contact with the same company_name. Adding the 1st one is not a problem, everything works fine. However for the 2nd Contact an issue appear when I add this code.
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() sqlalchemy.exc.IntegrityError: (psycopg2.errors.UniqueViolation) duplicate key value violates unique constraint "company_company_name_key" DETAIL: Key (company_name)=(bla) already exists.
I don't know how to write it to allow, two Contact with the same company and also to allow two Company with same Contact.
Thank you so much for your help.