使用 Flask、SQLAlchemy 和 WTForms 获取多对多关系中的用户选择数据

get user choice data in many-to-many relationships using Flask, SQLAlchemy and WTForms

这是我的第一个编码 python/flask/sqlalchemy 项目。 我想创建一个页面,HR 可以在其中 将选定的项目分配给选定的员工。 一名员工可以处理多个项目。许多员工可以在一个项目中工作(多对多关系)。

我的问题,我无法为选定的员工获取选定的项目并填写协会table。我试图搜索但找不到相关主题。感谢您的回复!

数据库部分的代码
my_db.py:

Employee_Task = db.Table('employee_task',
                         db.Column('employee_id', db.Integer, db.ForeignKey('employee.employee_id')),
                         db.Column('task_id', db.Integer, db.ForeignKey('task.task_id'))
                         )


class Employee(db.Model):
    __tablename__ = 'employee'
    employee_id = db.Column(db.Integer, primary_key=True)
    employee_name = db.Column(db.String(100), nullable=True)
    rel_task = db.relationship("Task", secondary=Employee_Task)


# class Task
class Task(db.Model):
    __tablename__ = 'task'
    task_id = db.Column(db.Integer, primary_key=True)
    task_name = db.Column(db.String(100), nullable=True)

    def __repr__(self):
        return "<Task %r>" % self.name

主要代码的一部分,如您所见,它添加了具有相同 employee_idtask_id[=35= 的新行], 但我想用 choosen employee_id 添加新行 choosen task_id

Let's say when HR assign to 5th employee 8th project, I want to see in one row of association table:
5 in employee_id column
8 in project_id column

main.py:

@app.route("/employee", methods=['POST', 'GET'])
def employee():
    tasks_all = Task.query.all()
    workers_all = Employee.query.all()
    if request.method == 'POST'
        idS = str(int(request.form.get("Assigned_Task")))
        EmployeeID = idS[0] #this is choosen employee, I want add this employee to association table 
        TaskID = idS[-1] #this is choosen project, I want add this project to association table
        e = Employee()
        t = Task()
        e.rel_task.append(t)
        db.session.add(e)
        db.session.commit()
    return render_template('my.html', tasks_all=tasks_all, workers_all=workers_all, form=search,
                           title='List of Employee')

html 页面的一部分(如您所见,它是 table,对于给定的员工列表,HR 可以从下拉菜单中选择一个项目并进行分配)

        <table class="table table-hover">
            <thread>
                <tr class="table-info font-italic">
                    <th>Employees</th>
                    <th>Projects</th>
                </tr>
            </thread>
            <tbody>
                {% for worker in workers_all %}
                <tr>
                    <td rowspan="1">{{ worker.employee_name }}</td>
                    <td rowspan>
                        <form action="/employee" method="POST">
                            <div class="input-group">
                                <select class="form-control" name="Assigned_Task">
                                    {% for task in tasks_all %}
                                        <option value="{{ worker.employee_id }} , {{ task.task_id }}">
                                            {{ task.task_name }}
                                        </option>
                                    {% endfor %}
                                </select>
                                <div class="input-group-append">
                                    <button type=submit value="" class="btn btn-sm btn-info">
                                        <i class="fas fa-user-check"></i>
                                        <a class="mr-1">assign</a>
                                    </button>
                                </div>
                            </div>
                        </form>
                    </td>
                </tr>
                {% endfor %}
            </tbody>
        </table>

我猜你发送的是元组的字符串表示形式。你必须转换它。您可以通过导入 python 内置 ast 库来实现。

import ast

@app.route("/employee", methods=['POST', 'GET'])
def employee():
    tasks_all = Task.query.all()
    workers_all = Employee.query.all()
    if request.method == 'POST'
        idS = ast.literal_eval(request.form.get("Assigned_Task"))
        Employee.id, Task.id = idS
        e = Employee()
        t = Task()
        e.rel_task.append(t)
        db.session.add(e)
        db.session.commit()
    return render_template('my.html', tasks_all=tasks_all, workers_all=workers_all, form=search,
                           title='List of Employee')

main.py:

@app.route("/employee", methods=['POST', 'GET'])
def employee():
    tasks_all = Task.query.all()
    workers_all = Employee.query.all()
    if request.method == 'POST'
        idS = str(int(request.form.get("Assigned_Task")))
        EmployeeID = idS[0]  
        TaskID = idS[-1] 
        e_qry = db.session.query(Employee).filter(Employee.employee_id.contains(EmployeeID))
        t_qry = db.session.query(Task).filter(Task.task_id.contains(TaskID))
        e = e_qry.first()
        t = t_qry.first()
        e.rel_task.append(t)
        db.session.add(e)
        db.session.commit()
    return render_template('my.html', tasks_all=tasks_all, workers_all=workers_all, form=search, title='List of Employee')