我在python中设置了以下SQLAlchemy模型:
class Relation(db.Model):
__tablename__ = 'relations'
relation_id = db.Column(
db.Integer,
primary_key=True,
autoincrement=True)
article_id = db.Column(
db.Integer,
db.ForeignKey("articles.id"),
nullable=False)
entity_id1 = db.Column(
db.Integer,
db.ForeignKey("entities.entity_id"),
nullable=False)
entity_id2 = db.Column(
db.Integer,
db.ForeignKey("entities.entity_id"),
nullable=False)
confidence = db.Column(
db.Integer
)
class Entity(db.Model):
__tablename__ = 'entities'
entity_id = db.Column(
db.Integer,
primary_key=True,
autoincrement=True)
name = db.Column(db.String(128), nullable=False)
我正在尝试将以下SQL查询字符串转换为SQLAlchemy查询(如果重要的话,请输入POSTGRES),并且主要目标是防止SQL注入:
SELECT DISTINCT e.name, e.entity_id FROM entities e RIGHT JOIN
relations r ON e.entity_id=r.entity_id1 OR e.entity_id=r.entity_id2
WHERE (r.entity_id1 = PARAMETER OR r.entity_id2 = PARAMETER)
AND e.entity_id<>PARAMETER;
这是我的尝试,但是我收到的错误消息表明联接存在问题:
relations = db.session.query(Entity).join(Relation.entity_id1)\ .join(Relation.entity_id2).distinct(Entity.name).filter((Relation.entity_id1 == PARAMETER)
| (Relation.entity_id2 == PARAMTER)
& (Entity.entity_id != PARAMETER))
任何建议或调试帮助将不胜感激!
编辑:有关用例的更多信息:“实体”是无向图的节点,“关系”是边。 (Relation.entity_id1 | Relation.entity_id2与Relation.entity_id2 | Relation.entity_id1相同)保证所有边缘源和目标都有相应的节点。给该目标一个entity_id = PARAMETER,找到该实体的所有相邻节点。