【问题标题】:Python Flask - Inserting into Tables with a Foreign KeyPython Flask - 使用外键插入表
【发布时间】:2022-01-22 13:42:48
【问题描述】:

在数据库关系方面需要帮助。 我有两张表:资金来源和分配摘要,两者之间有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'))

我的问题是,如果我需要 FundingSource 表中的这些属性,如何将属性“完整”、“代理”、“funding_source”和“bill”包含到 AllocationSummary() 并添加/提交到数据库?

我想我不明白“funding_source_id = db.Column(db.Integer, db.ForeignKey('funding_source.id'), nullable=False)” 是为了获得共同属性?

基本上,我需要:

my_alloc = AllocationSummary(complete, agency, funding_source, bill, state, qualified_applicant, 收件人, amount )

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

对不起,如果所有这些都令人困惑,我是新手。

【问题讨论】:

    标签: python database flask foreign-keys


    【解决方案1】:

    感谢allocations 关系,它是反向引用,您可以通过填充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()
        ...
    

    【讨论】:

    • 这绝对有道理!但是,当我尝试添加新分配时,出现此错误:TypeError: 'allocation' is an invalid keyword argument for FundingSource
    • 很抱歉,在这种情况下,您需要引用关系名称并提供一个列表。我已经为你更新了答案。
    • @Ez-Pz 我的编辑解决了你的问题吗?如果是,请将答案标记为已接受。
    • 谢谢,当我再次尝试时,它给了我错误:“NOT NULL 约束失败:funding_source.department”,因为部门是 FundingSource 表中的属性,但不是 AllocationSummary 表中的属性。虽然它不能为空,但我也不需要它来插入。那么我应该如何将它包含在“my_fund_src”中而不插入它呢?感谢大家的帮助
    • 那是完全不同的情况。如果你不需要它来插入,那么根据定义它应该是可以为空的。
    猜你喜欢
    • 1970-01-01
    • 2019-04-13
    • 2012-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多