外键列填充为NULL

时间:2019-03-01 22:07:12

标签: python database python-3.x sqlite sqlalchemy

我正在尝试为员工创建外键tableView(_:editActionsForRowAt:) 。但是tableView(_:trailingSwipeActionsConfigurationForRowAt:) 列的值为NULL而不是1。

任何建议/建议都值得赞赏。谢谢。

department_id

输出:

department_id

输出应为:

from sqlalchemy import create_engine, ForeignKey, Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine = create_engine('sqlite:///db.sqlite3', echo=False)

Base = declarative_base()

Session = sessionmaker(bind=engine)
Session.configure(bind=engine)
session = Session()

class Department(Base):
    __tablename__ = 'department'

    id = Column(Integer, primary_key=True)
    department_name = Column(String)

class Employee(Base):
    __tablename__ = 'employee'

    id = Column(Integer, primary_key=True)
    employee_name = Column(String)
    department_id = Column(Integer, ForeignKey('department.id'))

Base.metadata.create_all(engine)

d = Department(department_name='electronics')
session.add(d)

e = Employee(employee_name='alice')
session.add(e)

session.commit()

2 个答案:

答案 0 :(得分:3)

您需要将department传递给employee对象:

e = Employee(employee_name='alice', department = d)

或者,您可以在departmentemployee之间引入many-to-many relationship

import os

from sqlalchemy import Column, DateTime, String, Integer, ForeignKey, func
from sqlalchemy.orm import relationship, backref
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
class Department(Base):
    __tablename__ = 'department'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    employees = relationship(
        'Employee',
        secondary='department_employee_link'
    )

class Employee(Base):
    __tablename__ = 'employee'
    id = Column(Integer, primary_key=True)
    name = Column(String)
    hired_on = Column(
        DateTime,
        default=func.now())
        departments = relationship(
        Department,
        secondary='department_employee_link'
    )


class DepartmentEmployeeLink(Base):
    __tablename__ = 'department_employee_link'
    department_id = Column(Integer, ForeignKey('department.id'), primary_key=True)
    employee_id = Column(Integer, ForeignKey('employee.id'), primary_key=True)

答案 1 :(得分:-1)

我不确定您为什么期望Alice的部门为1。部门ID没有设置,因此将其持久化为null。

如果您希望爱丽丝有一个独立的ID,则需要传递部门ID。

类似

e = Employee(employee_name ='alice',department_id = 1)

代替

e = Employee(employee_name ='alice')