在 python mongoengine 中通过计算属性查询
我想知道是否可以使用 python 中的 mongoengine 通过计算属性来查询 MongoDB 中的文档。
目前,我的模型如下所示:
class SnapshotIndicatorKeyValue(db.Document):
meta = {"collection": "snapshot_indicator_key_values"}
snapshot_id = db.ObjectIdField(nullable=False)
indicator_key_id = db.ObjectIdField(nullable=False)
value = db.FloatField(nullable=False)
created_at = db.DateTimeField()
updated_at = db.DateTimeField()
@property
def snapshot(self):
return Snapshot.objects(id=self.snapshot_id).first()
def indicator_key(self):
return IndicatorKey.objects(id=self.indicator_key_id).first()
当我执行 SnapshotIndicatorKeyValue .objects().first().snapshot
操作时,我可以访问 snapshot
属性。
但是当我尝试查询它时,它不起作用。例如:
SnapshotIndicatorKeyValue.objects(snapshot__date_time__lte=current_date_time)
我收到错误“mongoengine.errors.InvalidQueryError:无法解析字段“快照”``
有什么方法可以使其与查询一起使用吗? 我需要根据snapshot
的属性查询SnapshotIndicatorKeyValue
。
I wondered if it is possible to query documents in MongoDB by computed properties using mongoengine in python.
Currently, my model looks like this:
class SnapshotIndicatorKeyValue(db.Document):
meta = {"collection": "snapshot_indicator_key_values"}
snapshot_id = db.ObjectIdField(nullable=False)
indicator_key_id = db.ObjectIdField(nullable=False)
value = db.FloatField(nullable=False)
created_at = db.DateTimeField()
updated_at = db.DateTimeField()
@property
def snapshot(self):
return Snapshot.objects(id=self.snapshot_id).first()
def indicator_key(self):
return IndicatorKey.objects(id=self.indicator_key_id).first()
When I do for example SnapshotIndicatorKeyValue .objects().first().snapshot
, I can access the snapshot
property.
But when I try to query it, it doesn't work. For example:
SnapshotIndicatorKeyValue.objects(snapshot__date_time__lte=current_date_time)
I get the error `mongoengine.errors.InvalidQueryError: Cannot resolve field "snapshot"``
Is there any way to get this working with queries?
I need to query SnapshotIndicatorKeyValue
based on a property of snapshot
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了直接通过 mongoengine 查询
snapshot
属性,您可以在SnapshotIndicatorKeyValue< 中引用相关的
snapshot
对象而不是snapshot_id
/code> 文档定义。使用 参考字段 修改后的模型将如下所示:
您将连续保存
Snapshot
实例和SnapshotIndicatorKeyValue
实例,如下所示:然后您可以引用
snapshot
的任何属性 通过:In order to query the
snapshot
property directly through mongoengine, you can reference the relatedsnapshot
object rather than thesnapshot_id
in yourSnapshotIndicatorKeyValue
document definition.An amended model using a Reference field would be like this:
You would sucessively save an instance of
Snapshot
and an instance ofSnapshotIndicatorKeyValue
like this:You can then refer to any of the
snapshot
's properties through: