首页 \ 问答 \ SQLAlchemy ORM __init__方法与(SQLAlchemy ORM __init__ method vs)

SQLAlchemy ORM __init__方法与(SQLAlchemy ORM __init__ method vs)

SQLAlchemy ORM教程中 ,下面的代码作为将被映射到表的类的示例给出:

>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
...     __tablename__ = 'users'
...
...     id = Column(Integer, primary_key=True)
...     name = Column(String)
...     fullname = Column(String)
...     password = Column(String)
...
...     def __init__(self, name, fullname, password):
...         self.name = name
...         self.fullname = fullname
...         self.password = password
...
...     def __repr__(self):
...        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)

如果用户在类实例化时在__init__方法中设置了namefullname namepassword ,那么将它们声明为Column对象(即作为类变量)有什么意义? 我不明白SQLAlchemy如何以及何时能够使用这些信息 - 它是否通过User继承的'Base'类传递给SQLAlchemy模块? (我认为不可能以这种方式将信息传递给一个单元 - 通过声明一个继承自另一个类的类)。


In the SQLAlchemy ORM tutorial the following code is given as an example of a class which will be mapped to a table:

>>> from sqlalchemy import Column, Integer, String
>>> class User(Base):
...     __tablename__ = 'users'
...
...     id = Column(Integer, primary_key=True)
...     name = Column(String)
...     fullname = Column(String)
...     password = Column(String)
...
...     def __init__(self, name, fullname, password):
...         self.name = name
...         self.fullname = fullname
...         self.password = password
...
...     def __repr__(self):
...        return "<User('%s','%s', '%s')>" % (self.name, self.fullname, self.password)

If name, fullname and password are set by the user in the __init__ method when the class is instantiated, what's the point of having them declared as Column objects (i.e as class variables)? I don't understand how and when SQLAlchemy is able to use the information - is it somehow passed to the SQLAlchemy module via the 'Base' class which User is inheriting from? (I didn't think it was possible to pass information to a unit in this way - by declaring a class which inherits from another class).


原文:https://stackoverflow.com/questions/19258471
更新时间:2023-12-15 14:12

最满意答案

这里的想法是首先按version键对文档进行排序,按title键对文档进行分组,并在订购时返回组中的第一个文档。 因此,邀请到此处聚合管道的运营商将是$sort$group$project (它将聚合文档重新整形为所需的结果模式)。

现在,在$group管道中,您需要$first运算符(或者$last具体取决于您在先前的$sort管道中订购文档的方向),以便在订购时映射顶层文档的字段。

考虑mongo shell中的以下游戏:

db.collection.aggregate([
    { "$sort": { "_id.version": -1 } },
    {
        "$group": {
            "_id": "$_id.title",
            "id": { "$first": "$_id" },
            "status": { "$first": "$status" }
            ...
        }
    },
    {
        "$project": {
            "_id": "$id",
            "status": 1,
            ...
        } 
    }
])

对于mongoTemplate等价物:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation agg = newAggregation(
    sort(DESC, "_id.version"),
    group("_id.title"), 
        .first("status").as("status")
        ...
    project("id").previousOperation().and("status").and(...)
);

您还可以选择将$$ROOT系统变量邀请到$group管道作为返回完整文档的方法。 考虑以下方法:

db.collection.aggregate([
    { "$sort": { "_id.version": -1 } },
    {
        "$group": {
            "_id": "$_id.title",            
            "doc": { "$first": "$$ROOT" }
        }
    },
    {
        "$project": {
            "_id": "$doc._id",
            "status": "$doc.status",
            ...
        } 
    }
])

这会转化为

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation agg = newAggregation(
    sort(DESC, "_id.version"),
    group("_id.title"), 
        .first(ROOT).as("doc")
    project("doc.status").as("status")...
);

The idea here is to order the documents by the version key first, group the documents by the title key and return the first document in the group when ordered. So, the operators invited to the aggregation pipeline show here will be the the $sort, $group and $project (which reshapes the aggregated documents to be in the desired result schema).

Now within the $group pipeline you'd need the $first operator (or $last depending on the direction which you ordered the documents in the previous $sort pipeline) to map the top document's field when ordered.

Consider the following play in mongo shell:

db.collection.aggregate([
    { "$sort": { "_id.version": -1 } },
    {
        "$group": {
            "_id": "$_id.title",
            "id": { "$first": "$_id" },
            "status": { "$first": "$status" }
            ...
        }
    },
    {
        "$project": {
            "_id": "$id",
            "status": 1,
            ...
        } 
    }
])

For the mongoTemplate equivalent:

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation agg = newAggregation(
    sort(DESC, "_id.version"),
    group("_id.title"), 
        .first("status").as("status")
        ...
    project("id").previousOperation().and("status").and(...)
);

You've got another alternative of inviting the $$ROOT system variable to your $group pipeline as means to return the full document. Consider the following approach:

db.collection.aggregate([
    { "$sort": { "_id.version": -1 } },
    {
        "$group": {
            "_id": "$_id.title",            
            "doc": { "$first": "$$ROOT" }
        }
    },
    {
        "$project": {
            "_id": "$doc._id",
            "status": "$doc.status",
            ...
        } 
    }
])

which would translate to

import static org.springframework.data.mongodb.core.aggregation.Aggregation.*;

Aggregation agg = newAggregation(
    sort(DESC, "_id.version"),
    group("_id.title"), 
        .first(ROOT).as("doc")
    project("doc.status").as("status")...
);

相关问答

更多

相关文章

更多

最新问答

更多
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)
  • 是否可以嵌套hazelcast IMaps?(Is it possible to nest hazelcast IMaps? And whick side effects can I expect? Is it a good Idea anyway?)
  • UIViewAnimationOptionRepeat在两个动画之间暂停(UIViewAnimationOptionRepeat pausing in between two animations)
  • 在x-kendo-template中使用Razor查询(Using Razor query within x-kendo-template)
  • 在BeautifulSoup中替换文本而不转义(Replace text without escaping in BeautifulSoup)
  • 如何在存根或模拟不存在的方法时配置Rspec以引发错误?(How can I configure Rspec to raise error when stubbing or mocking non-existing methods?)
  • asp用javascript(asp with javascript)
  • “%()s”在sql查询中的含义是什么?(What does “%()s” means in sql query?)
  • 如何为其编辑的内容提供自定义UITableViewCell上下文?(How to give a custom UITableViewCell context of what it is editing?)
  • c ++十进制到二进制,然后使用操作,然后回到十进制(c++ Decimal to binary, then use operation, then back to decimal)
  • 以编程方式创建视频?(Create videos programmatically?)
  • 无法在BeautifulSoup中正确解析数据(Unable to parse data correctly in BeautifulSoup)
  • webform和mvc的区别 知乎
  • 如何使用wadl2java生成REST服务模板,其中POST / PUT方法具有参数?(How do you generate REST service template with wadl2java where POST/PUT methods have parameters?)
  • 我无法理解我的travis构建有什么问题(I am having trouble understanding what is wrong with my travis build)
  • iOS9 Scope Bar出现在Search Bar后面或旁边(iOS9 Scope Bar appears either behind or beside Search Bar)
  • 为什么开机慢上面还显示;Inetrnet,Explorer
  • 有关调用远程WCF服务的超时问题(Timeout Question about Invoking a Remote WCF Service)