【问题标题】:SQLAlchemy query parent to find all childrenSQLAlchemy 查询父级以查找所有子级
【发布时间】: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


    【解决方案1】:

    Company.query.all() 返回公司列表。正如你所说,你必须遍历这些。如果您想获得名字,这同样适用于买家。

    我已将您的示例缩减到最低限度,以使其更易于理解。

    class Company(db.Model):
        __tablename__ = 'companies'
    
        id = db.Column(db.Integer, primary_key=True)
        name = db.Column(db.String(64), index=True, nullable=False)
    
        buyers = db.relationship('Buyer', backref='company', lazy='dynamic')
    
    class Buyer(db.Model):
        __tablename__ = 'buyers'
    
        id = db.Column(db.Integer, primary_key=True)
        firstname = db.Column(db.String(64), index=True, nullable=False)
        lastname = db.Column(db.String(64), index=True, nullable=False)
    
        company_id = db.Column(db.Integer, db.ForeignKey('companies.id'))
    
    class ListCompanies(MethodView):
        template_file = 'dashboard.html'
        def get(self):
            companies = Company.query.all()
            return render_template(self.template_file, companies=companies)
    
    <ul>
    {% for company in companies %}
        <li>
          <span>{{ company.name }}</span>
          <ul>
          {% for buyer in company.buyers %}
            <li>{{ buyer.lastname }}, {{ buyer.firstname }}</li>
          {% endfor %}
          </ul>
        </li>
    {% endfor %}
    </ul>
    

    【讨论】:

    • 太棒了。谢谢!我很感激。
    猜你喜欢
    • 2022-10-29
    • 2020-11-14
    • 2018-05-06
    • 1970-01-01
    • 2013-10-03
    • 2015-11-15
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多