When using SQLAlchemy there are for example two classes describing the User and Contact tables. At the same time Contact has a connection many to one to each line on User.

class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True) name = Column(String, nullable=False, unique=True) class Contact(Base): __tablename__ = "contact" id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('user.id')) contact = Column(String, nullable=False, unique=True) 

Is it possible, and if so, how, to describe a function in the User class of type add_contact, which will add an entry to the Contact table?

    1 answer 1

    The task is not quite clear, but if you really want it, then you can of course:

     class User(Base): __tablename__ = "user" id = Column(Integer, primary_key=True) name = Column(String, nullable=False, unique=True) def add_contact(self, contact): contact.user_id = self.id db_session.add(contact) db_session.commit() # ИЛИ def add_contact(self, contact_name): contact = Contact(user_id = self.id, contact = contact_name) db_session.add(contact) db_session.commit() class Contact(Base): __tablename__ = "contact" id = Column(Integer, primary_key=True) user_id = Column(Integer, ForeignKey('user.id')) contact = Column(String, nullable=False, unique=True) user = relationship(User, backref=backref("contacts")) def __init__(self, user_id, contact_name): self.user_id = user_id self.contact = contact_name