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__
方法中设置了name
,fullname
name
和password
,那么将它们声明为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
andpassword
are set by the user in the__init__
method when the class is instantiated, what's the point of having them declared asColumn
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 whichUser
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
最满意答案
这里的想法是首先按
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 thetitle
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")... );
相关问答
更多-
这里的想法是首先按version键对文档进行排序,按title键对文档进行分组,并在订购时返回组中的第一个文档。 因此,邀请到此处聚合管道的运营商将是$sort , $group和$project (它将聚合文档重新整形为所需的结果模式)。 现在,在$group管道中,您需要$first运算符(或者$last具体取决于您在先前的$sort管道中订购文档的方向),以便在订购时映射顶层文档的字段。 考虑mongo shell中的以下游戏: db.collection.aggregate([ { "$so ...
-
你的聚合查询需要$unwind for opennig to "sections"数组 添加您的聚合查询 {$unwind : "$sections"} 和你的重构聚合查询这样 db.collection.aggregate( [ {$unwind : "$sections"}, { "$match": { "_id": ObjectId("571c5c87faf473f40fd0317c") } }, { ...
-
尝试这个: SELECT CAST(
AS XML).query('count(//dtl)') FROM 例如: DECLARE @x NVARCHAR(MAX) SET @x = ' aj 1 7 ... -
我认为没有理由由于存在那些大型列而导致查询性能受损。 当您读取该数据时会出现性能问题 - 特别是当您需要数据库引擎返回文档时,但您(当然)在查询中没有这样做。 在内部,对于各种yada(max)数据类型,SQL在行中存储16个左右的字节指针(或引用标记,转发记录或它们称之为的任何内容),并且实际数据存储在一组单独的页面中。 因此,如果您不读取该列,则不需要访问这些页面,也不会导致磁盘I / O命中。 I see no reason why the performance of your query woul ...
-
使用表别名来区分表,而不必使用完整的表名: SELECT t1.field1, t1.field2, t2.field3, t2.field4, t3.field5, (SELECT MAX(at.age) FROM AGE_TABLE at WHERE at.person = t2.person) AS max_age FROM TABLE1 t1 JOIN TABLE2 t2 ON t2.person = t1.person JOIN ...
-
我不是Python专家,所以我会用JavaScript编写它。 您可以使用$sort , $group和$first操作者在聚合框架中执行此操作: db.col.aggregate([ {$sort: {created:-1}}, {$group: {_id: '$hash', num_sold: {$first: '$num_sold'}, _id_seen: {$first: '$_id'}}} ]) 基本上,我所做的就是根据创建日期DESC对传入文档进行排序,然后对散列进行分组,并将 ...
-
这样的事情应该有效(C#): var results = from x in db.table group x by x.title into g select g.OrderByDescending(x => x.date) .First(); 现在要进行正确的分页,你必须像这样调用整个查询的Skip / Take : var results = (from x in db.table group x by x.title into ...
-
使用mongo更新文档嵌套密钥更新使用$elemMatch查询,如下所示 db.collectionName.update({"source":{"$elemMatch":{"bookid":ObjectId("552cd77e31456e192df6ad8e")}}},{"$set":{"source.$.isActive":false}}) 如果多个文档更新然后使用此mongo更新添加多个true。 Use mongo update documentation for nesting key upda ...
-
你可以在两个查询中执行此操作,这可能更容易阅读。 第一个查询是获得最大高度和宽度所需要的。 然后,您可以发出第二个查询,如下所示: SElECT primaryId FROM ( SELECT imgHeight, imgWidth, imgId AS primaryId FROM primary_images UNION SELECT imgHeight, imgWidth, primaryId FROM secondary_images ) as union_table WHER ...
-
尝试以下方法名称: findFirstByOrderByCounterDesc https://docs.spring.io/spring-data/mongodb/docs/2.0.1.RELEASE/reference/html/ Try the following method name: findFirstByOrderByCounterDesc https://docs.spring.io/spring-data/mongodb/docs/2.0.1.RELEASE/reference/html/ ...