【发布时间】:2020-07-17 19:53:52
【问题描述】:
我有一个数据库,其中我有从父母(公司)到孩子(买家)的一对多关系。我想遍历每家公司以列出该公司的所有买家并在我的 html 页面中列出。
我最初的尝试是尝试companies = Company.query.all(),然后使用类似 `companies.buyer.firstname 的方式访问它,但这会报错
'list' 对象没有属性'buyer'
非常感谢任何帮助。谢谢!
view.py
class ListCompanies(MethodView):
decorators = [login_required]
template_file = 'dashboard.html'
def get(self):
companies = Company.query.all()
print(f'buyer is {companies.buyer.firstname}')
return render_template(self.template_file, companies=companies)
Models.py
class Company(db.Model, UserMixin):
__tablename__ = 'company'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True, nullable=False)
company = db.Column(db.String(64), index=True, nullable=False)
company_url = db.Column(db.String(64), index=True, nullable=False)
# Child relationship to the Event
event_id = db.Column(db.Integer, db.ForeignKey('events.id'))
password_hash = db.Column(db.String(128))
# Company is parent to the buyer
buyer = db.relationship('Buyers', backref='buyer', lazy='dynamic')
def __init__(
self, email, company, company_url, event_id, password
):
self.email = email
self.company = company
self.company_url = company_url
self.event_id = event_id
self.password_hash = generate_password_hash(password)
# self.user_type = user_type
def check_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return f"{self.company}"
class Buyers(db.Model, UserMixin):
__tablename__ = 'buyers'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(64), unique=True, index=True, nullable=False)
firstname = db.Column(db.String(64), index=True, nullable=False)
lastname = db.Column(db.String(64), index=True, nullable=False)
# The buyer is the child to the company
company = db.Column(db.Integer, db.ForeignKey('company.id'))
# The buyer is the parent to the eventdetails
details = db.relationship('Eventdetails', backref='buyer', lazy='dynamic')
def __init__(
self, email, firstname, lastname, company
):
self.email = email
self.firstname = firstname
self.lastname = lastname
self.company = company
def __repr__(self):
return f"Welcome, {self.firstname} {self.lastname}"
【问题讨论】:
标签: python-3.x flask flask-sqlalchemy