与其他表建立关系时,不会填充Sqlalchemy ID字段

时间:2015-04-21 00:43:47

标签: python sqlite sqlalchemy

我正在尝试设置Sqlalchemy,并且遇到了在表之间建立关系的问题。很可能是我的误解。

表格就是这样设置的。重要的一行是两面都有两个星号的那一行,建立了与表格#34;工作的关系。"

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)

现在,作业表紧随其后。检查带星号的行:

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))

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

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字段。根据

,不应该使用jobs表中的主键(id)填充它
job_id = Column(Integer, ForeignKey('jobs.id'))
或者我错过了什么?我假设我要编写代码来做到这一点,但我不想打破Sqlalchemy在后端尝试做的任何事情。这对于许多时钟来说应该是一个工作,因为一个人每个任务可以花费几天时间。

Clocktimes Table

1 个答案:

答案 0 :(得分:0)

检查docs它 看起来您已在ClockTime Job上设置clocktimes.job对象集合,ClockTime 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,因此永远不会触发ForeignKey的人口。

我认为您希望在列定义中添加job_id来执行它不会做的事情。您放在id上的{{1}}约束只是意味着它被约束为Jobs表的{{1}}列中存在的值。查看here了解详情