Flask-SQLalchemy一对一关系:将子级与现有父级关联?

时间:2018-12-07 15:19:19

标签: python-3.x sqlalchemy flask-sqlalchemy

第一次使用sqlalchemy和flask,我想念一些东西

我正在尝试使用Flask-SQLalchemy在两个表之间建立一对一的关系。

这是我的第一张桌子(父母)

class User(db.Model):
__tablename__ = 'users'

user_id = Column(Integer, primary_key=True, autoincrement=True)
user_email = Column(String(150), nullable=False)
user_password = Column(String(60), nullable=False)
child_employee = relationship('Employee', uselist=False, backref='users')

def __init__(self, user_email, user_password):
    self.user_email = user_email
    self.user_password = user_password

还有孩子

class Employee(User):
__tablename__ = 'employees'

employee_id = Column(Integer, primary_key=True, autoincrement=True)
user_id = Column(Integer, ForeignKey('users.user_id'), nullable=False)
employee_lastname = Column(String(30), nullable=False)
employee_firstname = Column(String(30), nullable=False)
employee_comment = Column(String)

def __init__(self, user_email, user_password, employee_lastname, employee_firstname, employee_comment=None):
    super().__init__(user_email, user_password)
    self.employee_lastname = employee_lastname
    self.employee_firstname = employee_firstname
    self.employee_comment = employee_comment

知道创建用户时,我的表“ users”中有一个用户,而表的“ employees”中则没有任何内容:这很有意义,很完美

然后,如果我创建了一个雇员,则在“员工”表中有一个新条目,在“用户”表中有一个新条目。它们彼此关联:这也很有意义,很完美

现在是问题: 我创建了一个用户,所以没有员工链接到该用户。 现在,我想创建一个员工,并将其链接到已经存在的用户,该怎么做?

我尝试过

# creation of the new employee
  new_employee = Employee(exisiting_user.user_email, 
    exisiting_user.user_password, "email", "lastname", "firstname")
  #trying to associate the new employee to the already existing user
  exisiting_user.child_employee = new_employee
  # save the employee to the database
  db.session.add(new_employee)
  db.session.commit()

但是我得到这个错误

sqlalchemy.exc.IntegrityError: (psycopg2.IntegrityError) duplicate key value violates unique constraint "users_pkey"
DETAIL:  Key (user_id)=(2) already exists.

 [SQL: 'INSERT INTO users (user_id, user_email, user_password) VALUES (%(user_id)s, %(user_email)s, %(user_password)s)'] [parameters: {'user_id': 2, 'user_email': 'email', 'user_password': 'password'}] 

谢谢 ----------------首先尝试解决它------------------------- 就像我理解正确一样,当我创建“ Employee”的实例时,我也有一个超类“ User”的实例。然后,当我db.session.add(new_employee)时,SQLalchemy为该雇员然后为该用户创建一个INSERT,但是该用户已经存在,所以出现错误。

我更改了Employee表:

class Employee(User):
__tablename__ = 'employees'

employee_id = Column(Integer, ForeignKey(User.user_id), primary_key=True)
employee_lastname = Column(String(30), nullable=False)
employee_firstname = Column(String(30), nullable=False)
employee_comment = Column(String)
parent = relationship("User", back_populates="child_employee")

def __init__(self, employee_id, employee_lastname, employee_firstname, employee_comment=None):
    self.employee_id = employee_id
    self.employee_lastname = employee_lastname
    self.employee_firstname = employee_firstname
    self.employee_comment = employee_comment

并仅添加我正在工作的员工

emp = Employee(1, "lastname", "firstname", "comment")
db.session.execute("INSERT INTO employees VALUES("emp.employee_id",'"emp.employee_lastname+"', '"+emp.employee_firstname+"', '"+emp.employee_comment+"')")

由于ID也是外键,因此员工和用户会自动链接

它可以工作,但是我更喜欢使用db.session.add(emp)之类的更简单的东西,我仍然想念一些东西

0 个答案:

没有答案