SqlAlchemy Help:尝试将子项添加到子项中

时间:2018-02-05 15:01:31

标签: python sqlalchemy

我有这个数据库架构:

class Profile_Eval(Base):
    __tablename__ = 'profile_eval'
    id = Column(Integer, primary_key=True)
    url = Column(String(), unique=True)

    job_descriptions = relationship("Job_Description", back_populates='profile')


    def __init__(self, url=None):
        self.url = url

class Job_Description(Base):
    __tablename__ = 'job_description'
    id = Column(Integer, primary_key=True)
    data = Column(String())
    profile_eval_id = Column(Integer, ForeignKey('profile_eval.id'))

    profile = relationship("Profile_Eval", back_populates='job_descriptions')

    job_predictions= relationship("Job_Prediction", back_populates='job_description')

    def __init__(self, data=None, profile_eval_id=None):
        self.data = data

class Job_Prediction(Base):
    __tablename__ = 'job_prediction'
    id = Column(Integer, primary_key=True)
    label = Column(String())
    score = Column(String())

    job_description_id = Column(Integer, ForeignKey('job_description.id'))

    job_description = relationship("Job_Description", back_populates="job_predictions")

    def __init__(self, label=None, score=None, job_description_id=None):
        self.label = label
        self.score = score

结构是每个配置文件都有很多工作。每项工作都有很多预测。

我可以添加如下个人资料:

profile = Profile_Eval(url=url)

然后我可以将作业描述添加到配置文件中,如:

profile_record.job_descriptions.append(Job_Description(description))

但现在我对如何在每个描述中添加predictions感到困惑。

我应该将它分解到自己的表中并摆脱relationship吗?或者有没有办法添加它们?

谢谢!

1 个答案:

答案 0 :(得分:0)

  

我应该把它分解成自己的表并摆脱这种关系吗?

Job_Prediction已经是它自己的表了。

  

或者有没有办法添加它们?

是的,在您将描述添加到作业的同时为说明添加预测:

job_description = Job_Description(description)
job_description.job_predictions.append(...)
#                                      ^^^ whetever you need, here
profile_record.job_descriptions.append(job_description)