Python Flask-使用外键插入到表中



需要数据库关系方面的帮助。我有两个表:资金来源和分配汇总,并且4的属性在两者之间是相同的。我使用外键,因为这两个表之间存在一对多的关系——一个资金来源可以有很多分配,但一个分配只能有一个资金源:

这是我的两张桌子:

class FundingSource(db.Model):
id = db.Column(db.Integer, primary_key=True)
complete = db.Column(db.String(10), default=False, nullable=False)
department = db.Column(db.String(100), nullable=False)
agency = db.Column(db.String(150), nullable=False)
funding_source = db.Column(db.String(200), nullable=False)
bill = db.Column(db.String(10), nullable=False)
tracker = db.Column(db.String(255), nullable=False)
allocations = db.relationship('AllocationSummary', backref='allocation', lazy=True) 

class AllocationSummary(db.Model):
id = db.Column(db.Integer, primary_key=True)
# complete 
# agency 
# funding_source 
# bill
state = db.Column(db.String(100), nullable=False)
recipient = db.Column(db.String(200), nullable=False)
amount = db.Column(db.Float(), nullable=False)
funding_source_id = db.Column(db.Integer, db.ForeignKey('funding_source.id'), nullable=False)
def __init__(self, state, eligible_applicant, recipient, amount):
self.state = state
self.eligible_applicant = eligible_applicant
self.recipient = recipient
self.amount = amount

在我的分配汇总网页中,我有一个插入新分配的按钮,要求您填写表格字段。

这是我的代码,用于插入具有所需表单字段的新分配:

@main.route("/insert", methods=['POST'])
def insert():
if request.method == 'POST':
complete = request.form['complete']
agency = request.form['agency']
funding_source = request.form['funding_source']
bill = request.form['bill']
state = request.form['state']
eligible_applicant = request.form['eligible_applicant']
recipient = request.form['recipient']
amount = request.form['amount']
my_alloc = AllocationSummary(state, eligible_applicant, recipient, amount)
db.session.add(my_alloc)
db.session.commit()
return redirect(url_for('alloc_summ'))

我的问题是,我如何将属性";完整"代理"funding_source";,以及";账单;如果我需要FundingSource表中的那些属性,请将其添加到AllocationSummary((并将其添加/提交到数据库?

我想我不明白";funding_source_id=db。列(db.Integer,db.ForeignKey('funding_source.id'(,nullable=False("假设是为了获得公共属性?

本质上,我需要:

my_alloc=分配汇总(完成代理资金来源票据(

但是我无法访问这些属性,因为它们在FundingSource表中,所以在插入时如何将它们推送到数据库?

很抱歉,如果这一切让人困惑,我是新手。

由于allocations关系及其backref,您可以通过填充AllocationSummary对象并将其传递给FundingSource来实现它。但是,只有当您从模型中删除__init__函数时,这才会起作用。

...
complete = request.form['complete']
agency = request.form['agency']
funding_source = request.form['funding_source']
bill = request.form['bill']
state = request.form['state']
eligible_applicant = request.form['eligible_applicant']
recipient = request.form['recipient']
amount = request.form['amount']
my_fund_src = FundingSource(
complete=complete,
agency,
funding_source,
bill=bill,
allocations=[
AllocationSummary(
state=state,
eligible_applicant=eligible_applicant,
recipient=recipient,
amount=amount
)
]
)
db.session.add(my_fund_src)
db.session.commit()
...

相关内容

  • 没有找到相关文章

最新更新