简体   繁体   English

标记sqlalchemy表中的列

[英]marking columns in sqlalchemy tables

I'd like to add a custom attribute "searchable" to the columns in an sqlalchemy model. 我想在sqlalchemy模型中的列中添加自定义属性“searchable”。 The purpose is to extract data for just these columns (using ModelFoo.__ table__.columns) and put the data into solr. 目的是仅为这些列提取数据(使用ModelFoo .__ table __。columns)并将数据放入solr。 Is there a way I can mark certain columns using a custom attribute? 有没有办法可以使用自定义属性标记某些列?

class ModelFoo(AppBase):
    __tablename__ = 'foo'
    id = Column("id", Integer, primary_key=True, autoincrement=True)
    os = Column(String, nullable=False, searchable=True)
    platform = Column(String, searchable=True)

by default, I get the following error when I try the above: 默认情况下,当我尝试上述操作时出现以下错误:

sqlalchemy.exc.ArgumentError: Unknown arguments passed to Column: ['searchable']

I am looking for a generic way to add only "searchable" columns to solr, something along these lines: 我正在寻找一种通用的方法来向solr添加“可搜索”列,这些内容如下:

for table in Base.metadata.tables.values():
    keys = [str(key) for key in table.columns if key.searchable] 
    solr.add(session.query(*keys).all())

in the above code, I am looking for some short solution or alternative to get "key.searchable" to work. 在上面的代码中,我正在寻找一些简短的解决方案或替代方案来使“key.searchable”工作。 Hope this clarifies the question. 希望这澄清了这个问题。

I solved this using a separate attribute in model: 我使用模型中的单独属性解决了这个问题:

class ModelFoo(Base):
    __tablename__ = 'foo'
    id = Column("id", Integer, primary_key=True, autoincrement=True)
    os = Column(String, nullable=False)
    platform = Column(String)
    search_cols = ["os", "value"]

for k, v in list(Base._decl_class_registry.items()):
    if (hasattr(v, "search_cols")):
        cols = [getattr(v, val) for val in v.search_cols]
        query = sess.query(*cols)
        solr.add(query.all())

I'm a little unclear on your question but it looks like your are trying to do something like this from the link you provided: 我对你的问题有点不清楚,但看起来你正试图通过你提供的链接做这样的事情:

si.add(Book.objects.all())

Where Book.objects.all() is a list of records from an ORM mapped table. 其中Book.objects.all()是来自ORM映射表的记录列表。 Note that the docs say a list of objects is also acceptable. 请注意,文档说对象列表也是可以接受的。 I think to solution here is to use the SQLAlchemy query method to build records with only the fields you want. 我认为这里的解决方案是使用SQLAlchemy查询方法来构建只包含所需字段的记录。 Using your example with would look like this: 使用您的示例将如下所示:

si.add(session.query(ModelFoo.os, ModelFoo.platform).all())

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

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