建立与另一个 table 的关系时,不会填充 SQLalchemy ID 字段

Sqlalchemy ID field isn't populated when relationship with another table is set up

我正在尝试设置 Sqlalchemy,但 运行 遇到了在 table 之间设置关系的问题。多半是我的误会。

一个table是这样设置的。重要的是两边有两个星号的那一行,建立与 table "jobs."

的关系
class Clocktime(Base):
"""Table for clockin/clockout values

ForeignKeys exist for Job and Employee
many to one -> employee
many to one -> job
"""

__tablename__ = "clocktimes"
id = Column(Integer, primary_key=True)
time_in = Column(DateTime)
time_out = Column(DateTime)
employee_id = Column(Integer, ForeignKey('employees.id'))
**job_id = Column(Integer, ForeignKey('jobs.id'))**
# employee = many to one relationship with Employee
# job = many to one relationship with Job

@property
def timeworked(self):
    return self.time_out - self.time_in

@property
def __str__(self):
    formatter="Employee: {employee.name}, "\
              "Job: {job.abbr}, "\
              "Start: {self.time_in}, "\
              "End: {self.time_out}, "\
              "Hours Worked: {self.timeworked}, "\
              "ID# {self.id}"
    return formatter.format(employee=self.employee, job=self.job, self=self)

现在,工作table接踵而至。检查带星号的行:

class Job(Base):
"""Table for jobs

one to many -> clocktimes
note that rate is cents/hr"""

__tablename__ = "jobs"
id = Column(Integer, primary_key=True)
name = Column(String(50))
abbr = Column(String(16))
rate = Column(Integer)  # cents/hr
**clocktimes = relationship('Clocktime', backref='job', order_by=id)**

def __str__(self):
    formatter = "Name: {name:<50} {abbr:>23}\n" \
                "Rate: ${rate:<7.2f}/hr {id:>62}"
    return formatter.format(name=self.name,
                            abbr="Abbr: " + str(self.abbr),
                            rate=self.rate/100.0,
                            id="ID# " + str(self.id))

当用户启动新任务时,执行以下代码以将相关数据写入 tables 作业和时钟:

new_task_job = [Job(abbr=abbrev, name=project_name, rate=p_rate), Clocktime(time_in=datetime.datetime.now())]
    for i in new_task_job:
        session.add(i)
    session.commit()
    start_time = datetime.datetime.now()
    status = 1

然后,当用户休息时...

new_break = Clocktime(time_out=datetime.datetime.now())
    session.add(new_break)
    session.commit()

如果您查看屏幕截图,job_id 字段未被填充。不应该用作业 table、per

中的主键 (id) 填充它吗
job_id = Column(Integer, ForeignKey('jobs.id'))

还是我遗漏了什么?我假设我要编写代码来执行此操作,但我不想破坏 Sqlalchemy 试图在后端执行的任何操作。这对许多时钟来说应该是一项工作,因为一个人可以为一项任务花费几天时间。

检查docs它 看起来您已经在 Job 上设置了一个名为 clocktimesClockTime 对象集合,并在 ClockTime 上设置了一个 .job 属性,该属性将引用父 Job 对象。

预期的行为是,

c1 = ClockTime()
j1 = Job()

>>> j1.clocktimes
[]
>>> print c1.job
None 

当您用一个对象填充 j1.clocktimes 时,您还应该看到 c1.job 得到一个非 None 值。

j1.clocktimes.append(c1)
>>> j1.clocktimes
[an instance of `ClockTime`]
>>> c1.job
[an instance of `Job`]

你发现这种行为了吗?我没有在您的代码中看到您填充 clocktimes 的位置,因此永远不会触发 job 的填充。

我认为您希望在列定义中添加 ForeignKey 来做一些它没有做的事情。您在 job_id 上设置的 ForeignKey 约束只是意味着它被限制在作业 table 的 id 列中存在的值中。检查 here 了解更多详情