简体   繁体   English

添加外键表时,Sqlalchemy添加不需要的列以进行查询

[英]Sqlalchemy adds unwanted columns to query when a foreign key table is added

In a Sqlalchemy query, you can select specific rows like this: 在Sqlalchemy查询中,您可以选择特定的行,如下所示:

q = session.query(Equipment.name)

That will return one column for each row. 这将为每一行返回一列。 You can add more column descriptors from model. 您可以从模型中添加更多列描述符。 The value of len(q.column_descriptions) is one in this case. 在这种情况下, len(q.column_descriptions)值为1。

However, as soon as you add a column that is a foreign key you suddenly get all the columns of the table, even though I didn't ask for them. 但是,一旦添加了作为外键的列,您就会突然获得表中的所有列,即使我没有要求它们也是如此。

q = dbsession.query(models.Equipment.name, models.Equipment.model)

This should be two columns, but now len(q.column_descriptions) is 15 (for this table, that's all of them plus the addidtional one). 这应该是两列,但现在len(q.column_descriptions)为15(对于此表,这些都是它们加上附加的)。

The query (q.statement) ends up looking like this: 查询(q.statement)最终看起来像这样:

SELECT public.equipment.name, public.equipment.id, public.equipment.model_id, public.equipment.serno, public.equipment.location_id, public.equipment.sublocation, public.equipment.addeddate, public.equipment.comments, public.equipment.language_id, public.equipment.owner_id, public.equipment.vendor_id, public.equipment.account_id, public.equipment.parent_id, public.equipment.active 
FROM public.equipment

I think this is a bug in Sqlalchemy, but maybe I'm doing something wrong and somebody here might know what it is. 我认为这是Sqlalchemy中的错误,但也许我做错了,这里的人可能知道这是什么。

"name" is a column. “名称”是一列。 "model" is not - its a relationship() (based on the observed behavior above). “模型”不是-它是一个Relationship()(基于上面观察到的行为)。 The current default __clause_element__() for relationship is the full table so that's why all columns get spit out. 当前用于关系的默认__clause_element__()是整个表,所以这就是为什么所有列都吐出来的原因。 As you noted in ticket #1328 this is related, but the proposal there is that you'd be getting back ('name', SomeModelObject), so not a foreign key column there either. 正如您在票证#1328中所指出的那样,这是相关的,但建议是您要返回(“ name”,SomeModelObject),因此也不是外键列。 The difference between "foreign key" and "relationship" is different in SQLAlchemy, in constrast to other ORM tools which may conceal the fact that "foreign key" columns exist. 在SQLAlchemy中,“外键”和“关系”之间的区别是不同的,这与其他ORM工具相反,后者可能掩盖了“外键”列存在的事实。

To query for the FK column only, you want to say query(Equipment.name, Equipment.model_id), or whatever the name of the foreign key column that references "model" is. 要仅查询FK列,您要说查询(Equipment.name,Equipment.model_id),或引用“模型”的外键列的名称。 If you're using Elixir then you may have to dig into their docs to see what name they use. 如果您使用的是Elixir,则可能必须深入研究他们的文档以查看他们使用的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM