I have the following one-to-many relationship in SQLAlchemy.
class Application(Base):
__tablename__ = "application"
id = Column("id", Integer, primary_key = True, autoincrement = True)
organization_id = Column(Integer, ForeignKey('organization.id'))
organization = relationship("Organization", uselist=False, back_populates="applications")
and
class Organization(Base):
__tablename__ = "organization"
id = Column("id", Integer, primary_key = True, autoincrement = True)
name = Column("name", String(128), unique = True, nullable = False)
applications = relationship("Application", back_populates="organization")
To put the relationship in words, "one organization can have many applications and an application can have a single organization".
The way I infer it is that the Organization
class is the parent and the Application
class is the child.
I have a .csv file that contains a list of applications. I'm parsing the list to create an instance of Application
and Organization
from each row. I then set application.organization = organization
, and then do session.add(application)
.
When I the application to the database, if the organization that is added in turn is being added the first time, it's inserted correctly. But when an application is found that has the same organization as one inserted before it complains of an error -
sqlalchemy.exc.IntegrityError: (pymysql.err.IntegrityError) (1062, "Duplicate entry 'MICROSOFT' for key 'name'")
I understand that this is because this organization already exists in the DB.
Won't SQLAlchemy take care of this case? If not, how do I handle this on my end?