2015-04-21 30 views
1

我正在尝试设置Sqlalchemy,并且遇到了设置表格之间关系的问题。这很可能是我的误解。当与另一张桌子的关系建立时,不填充Sqlalchemy ID字段

表设置为如此。重要的一行是两个星号之一,与表格“工作”建立关系。

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) 

现在,就业表如下。检查带星号线:

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 

然后,当:

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

当用户启动一个新的任务,下面的代码是为了编写有关数据表工作和clocktimes执行用户休息一下...

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

如果你看截图,job_id字段没有被填充。不应该使用来自作业表的主键(id)填充,根据

job_id = Column(Integer, ForeignKey('jobs.id')) 

或者我错过了什么?我假设我要编写代码来做到这一点,但我不想破坏Sqlalchemy试图在后端执行的任何操作。这对于许多时钟来说应该是一项工作,因为每个人可以花费数天时间完成每项任务。

Clocktimes Table

回答

0

检查出docs它 看起来你已经设置了对JobClockTime对象称为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来做一些它没有做的事情。您在job_id上放置的ForeignKey约束仅表示它受限于Jobs表的id列中的值。查询here了解更多详情

+0

说得没错。正如GIS世界所称的那样,我期待有一种“加入”。原来,我需要编写一些代码来自己设置它。我只是不完全确定它是否应该通过某种魔法自动处理,并且不愿意自己处理它,并且踩下本来应该存在的某些功能。 –

相关问题