SQLAlchemy - 通过引用从helper表中查询id

时间:2015-05-26 12:40:50

标签: python mysql flask sqlalchemy flask-sqlalchemy

我正在尝试构建一个灵活的数据库模型,允许我存储防火墙规则。我(为了清晰起见,通过删除不相关的部分略微简化)数据库模式如下所示:

DB schema

我的SQLAlchemy数据库模型(对于Flask项目)如下所示:

' '

现在我的问题是如何查询class FirewallRule(db.Model): id = db.Column(db.Integer, primary_key=True) src_ip = db.Column(db.String(32), nullable=True) dst_ip = db.Column(db.String(32), nullable=True) port_expression = db.relationship('PortExpression', backref='firewall_rules', lazy='dynamic') firewall_rule_protocol = db.relationship('Protocol', secondary=firewall_rule_protocol, lazy='dynamic', backref=db.backref('firewall_rules', lazy='dynamic')) def add_protocol(self, protocol_number): protocol = Protocol.query.filter_by(protocol_number=protocol_number).first() if protocol and protocol in self.firewall_rule_protocol: return if not protocol: return self.firewall_rule_protocol.append(protocol) class PortExpression(db.Model): id = db.Column(db.Integer, primary_key=True) direction = db.Column(db.String(3), nullable=True) port_expression = db.Column(db.String(32), nullable=False) firewall_rule_id = db.Column(db.Integer, db.ForeignKey('firewall_rule.id'), nullable=False) firewall_rule_protocol_id = db.Column(db.Integer, db.ForeignKey('firewall_rule_protocol.id'), nullable=False) def add_port_expr(self, direction, expr, firewall_rule_id, firewall_rule_protocol_id): firewall_rule=FirewallRule.query.filter_by(id=firewall_rule_id).first() self.direction = direction self.port_expression = expr self.firewall_rule_id = firewall_rule_id self.firewall_rule_protocol_id = firewall_rule_protocol_id class Protocol(db.Model): id = db.Column(db.Integer, primary_key=True) protocol_name = db.Column(db.String(8), nullable=False) protocol_number = db.Column(db.Integer, nullable=False) firewall_rule_protocol = db.Table('firewall_rule_protocol', db.Column('id', db.Integer, primary_key=True), db.Column('firewall_rule_id', db.Integer, db.ForeignKey('firewall_rule.id'), nullable=False), db.Column('protocol_id', db.Integer, db.ForeignKey('protocol.id'), nullable=False)) 表中与id记录相关的firewall_rule_protocol条记录?

在我的views.py中,我执行以下操作:

certain firewall_rule

以上失败,并显示以下错误消息:

    if form.validate_on_submit(): 
        firewall_rule = FirewallRule()
        form.populate_obj(firewall_rule)
        firewall_rule.add_protocol(form.protocol.data)
        db.session.add(firewall_rule)
        db.session.flush()
        if form.port.data:
            port = PortExpression()
            direction = None
            port.add_port_expr(None, form.port.data, firewall_rule.id, firewall_rule.firewall_rule_protocol.id)

port.add_port_expr(None, form.port.data, firewall_rule.id, firewall_rule.firewall_rule_protocol.id)

看起来我在做一些愚蠢的事情,但无法弄清楚自己是什么。提前感谢任何有关正确方向的帮助或指示。

此致 Sergiusz

0 个答案:

没有答案