我正在制作一个烧瓶应用程序,每个用户都可以将其员工添加到列表中。我有两个表:User和Employee,它们看起来像这样:
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
email = db.Column(db.String(120), index=True, unique=True)
password_hash = db.Column(db.String(128))
emps = db.relationship('Employee', backref = 'boss', lazy = 'dynamic')
def __repr__(self):
return '<User {}'.format(self.username)
def set_password(self, password):
self.password_hash = generate_password_hash(password)
def check_password(self, password):
return check_password_hash(self.password_hash, password)
class Employee(db.Model):
__tablename__ = 'Employees'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(64), index=True)
last_name = db.Column(db.String(64), index=True)
User_id = db.Column(db.Integer, db.ForeignKey(User.id))
def __repr__(self):
return '<Employee {0} {1}>'.format(self.first_name, self.last_name)
我尝试将其添加到我的User类中,以便我可以加入这两个表:
def user_employees(self):
user_emps = User.query.join(Employee, User.id == Employee.User_id).filter(User.id == Employee.User_id)
return user_emps
在我的html文件中,我有这个:
{% block content %}
{% for employee in employees %}
<div>{{ employee }}</div>
{% endfor %}
{% endblock %}
这是视图功能:
def Show_Employees():
employees = current_user.user_employees()
return render_template('emps.html', employees = employees)
然而,这不起作用。我只在我的页面上写了这个:
<User test
预期输出将是员工的名字和姓氏。 我想问题是加入,但我无法弄清楚。有没有人遇到类似的东西?
答案 0 :(得分:2)
您不必担心手动加入,SQLalchemy会为您解决所有这些问题。您可以通过user.emps
访问用户员工,该员工返回员工列表。我抛弃了很多你可以再次添加的代码,只是为了让这个例子变得简单易懂。它功能齐全:
from flask import Flask, render_template_string
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
app = Flask(__name__)
db = SQLAlchemy(app)
class User(UserMixin, db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(64), index=True, unique=True)
emps = db.relationship('Employee', backref = 'boss', lazy = 'dynamic')
class Employee(db.Model):
__tablename__ = 'Employees'
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(64), index=True)
User_id = db.Column(db.Integer, db.ForeignKey(User.id))
db.create_all() # creates the database tables, not needed if you already have them
boss1 = User()
boss1.username = 'Mr Boss'
employee1 = Employee()
employee1.first_name = 'Mr peanut'
employee2 = Employee()
employee2.first_name = 'Mr butter'
boss1.emps = [employee1, employee2] # here is where you're binding the employees to the user
db.session.add(boss1)
db.session.commit()
@app.route('/')
def index():
user = User.query.get(1) # this returns the user with id1, which is 'Mr boss'
return render_template_string('''
This is user {{user.username}}<br>
His empoyees are:
{% for employee in user.emps %}
<div>{{ employee.first_name }}</div>
{% endfor %}
''', user=user)
app.run()
如果您访问该网站,请打印:
This is user Mr Boss
His empoyees are:
Mr peanut
Mr butter