如何在SQLAlchemy

时间:2017-12-15 08:32:32

标签: python mysql flask flask-sqlalchemy

我有两个类模型,它们转换为两个MySQL数据库表。一个是employees,另一个是projects。他们有一对多的关系,即一个项目可以有几个员工。在我的网络表单中注册员工时,我有一个包含项目的下拉列表。表employees具有引用projects表的外键,因此employees表具有Integer列(emp_project_id)作为来自{{的外键1}}表。从下拉列表中选择项目时如何保存ID?

projects

这是class Employee(UserMixin, db.Model): """ Create Employee table """ # Ensures table will be named in plural and not in singular # as in the name of the model __tablename__ = 'employees' id = db.Column(db.Integer, primary_key=True) emp_number = db.Column(db.String(10), index=True, unique=True, nullable=False) username = db.Column(db.String(60), index=True, unique=True) email = db.Column(db.String(60), index=True, unique=True, nullable=False) emp_name = db.Column(db.String(100), index=True) password_hash = db.Column(db.String(128)) emp_project_id = db.Column(db.Integer, db.ForeignKey('projects.id'), nullable=False)

projects

如果可能的话,请告诉我我可以通过的资源,因为我没有在他们的文档中找到解决方案。

以下是class Project(db.Model): """ Create a Project table """ __tablename__ = 'projects' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(60), unique=True, nullable=False) description = db.Column(db.String(200), nullable=False) pro_subprojects = db.relationship('Subproject', backref='sp_project', lazy='dynamic') pro_employees = db.relationship('Employee', backref='emp_project', lazy='dynamic') 创建表单

的类
forms.py

以下是我在class RegistrationForm(FlaskForm): """ Form for users to create new account """ project = QuerySelectField(query_factory=lambda: Project.query.all(), get_label="name") subproject = QuerySelectField(query_factory=lambda: Subproject.query.all(), get_label="name") emp_number = StringField('Employee Number', validators=[DataRequired()]) email = StringField('Email', validators=[DataRequired(), Email()]) username = StringField('Username', validators=[DataRequired()]) emp_name = StringField('Full Name', validators=[DataRequired()]) password = PasswordField('Password', validators=[ DataRequired(), EqualTo('confirm_password') ]) confirm_password = PasswordField('Confirm Password') submit = SubmitField('Register') 上添加的内容:

views.py

但是当我尝试注册员工时,我收到了@auth.route('/register', methods=['GET', 'POST']) def register(): """ Handle requests to the /register route Add an employee to the database through the registration form """ form = RegistrationForm() if form.validate_on_submit(): employee = Employee(project=form.project.data, subproject=form.subproject.data, emp_number=form.emp_number.data, email=form.email.data, username=form.username.data, emp_name=form.emp_name.data, password=form.password.data) # add employee to the database db.session.add(employee) db.session.commit() flash('You have registered successfully. You can now log in.') 之类的错误。请帮助

1 个答案:

答案 0 :(得分:0)

这是the documentation for QuerySelectedField中的内容:

  

data属性实际上将存储/保留ORM模型实例,而不是   ID。

现在我理解你的问题会改变你的观点:

@auth.route('/register', methods=['GET', 'POST'])
def register():
    """
    Handle requests to the /register route
    Add an employee to the database through the registration form
    """
    form = RegistrationForm()
    if form.validate_on_submit():
        employee = Employee(
                            emp_number=form.emp_number.data,
                            email=form.email.data,
                            username=form.username.data,
                            emp_name=form.emp_name.data,
                            password=form.password.data)
        project=form.project.data  #an instance of Project Class
        subproject=form.subproject.data #an instance of SubProject Class
        project.pro_subproject.append(subproject) 
        project.pro_employee.append(employee)
        # add employee to the database
        db.session.add(employee)
        db.session.add(subproject)
        db.session.add(project)
        db.session.commit()
        flash('You have registered successfully. You can now log in.')

Here is an explanation of that :

  

一对多关系将外键放在子表上   引用父级。然后在。上指定 relationship()   parent,引用由表示的项集合   子:

这意味着在项目表中,字段pro_employees和pro_subproject是employee(n)和sub_project(n)的列表。