简体   繁体   English

从一个来源写入两个链接的flask-sqlalchemy模型

[英]Writing to two linked flask-sqlalchemy models from one source

I'm a beginner in flask, building a flask-based webapplication. 我是Flask的初学者,正在构建基于Flask的Web应用程序。 I'm using flask-sqlalchemy to connect to my sqlite db. 我正在使用flask-sqlalchemy连接到我的sqlite数据库。

When I import data from the form and write it to the database, the 'apple_id' column in the 'Pear' model contains NULL for every entry. 当我从表单导入数据并将其写入数据库时​​,“ Pear”模型中的“ apple_id”列的每个条目都包含NULL。 It's supposed to hold the ID of the 'Apple'-entry. 它应该保存“ Apple”条目的ID。 Other data is written as I expected. 其他数据按我的预期编写。 The two table have a one-to-many relationship, one apple can be referenced by multiple pears. 这两个表具有一对多关系,一个苹果可以被多个梨引用。

I simplified the script to make it easier to analyse. 我简化了脚本,使其更易于分析。

in models.py: 在models.py中:

from flask import current_app, request, url_for
from . import db

class Apple(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(64))

class Pear(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    apple_id = db.Column(db.Integer, db.ForeignKey('cabinet.id'))
    amount = db.Column(db.Integer)

In views.py 在views.py中

from . import edit
from flask import render_template, url_for, redirect, flash
from .forms import ApplePearForm
from ..models import Apple, Pear
from .. import db

@edit.route('/apples-and-pears', methods=['GET', 'POST'])
def apples_and_pears():
    form = ApplePearForm()
    if form.validate_on_submit():
        apple = Apple(name=form.name.data)
        db.session.add(apple)
        pear = Pear(apple_id=apple.id, amount=4)
        db.session.add(pear)
        flash('fruit was added to database')
        return redirect(url_for('browse.fruit_list'))
    return render_template('edit/apples_and_pears.html', form=form)

If you need a relationship between tables you should use relationship to define. 如果需要表之间的关系,则应使用relationship进行定义。 backref add reference on both side so you can do this pear=Pear(apple=apple) : backref在两侧都添加了引用,因此您可以执行以下pear=Pear(apple=apple)

class Apple(db.Model): 
    ...
    pears = db.relationship('Pear', backref='apple') 

class Pear(db.Model): 
    ...
    apple_id = db.Column(db.Integer, db.ForeignKey('cabinet.id')

#view 
apple = Apple(...)
pear = Pear(apple=apple, ...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM