Skip to content
Advertisement

Query by computed property in python mongoengine

I wondered if it is possible to query documents in MongoDB by computed properties using mongoengine in python.

Currently, my model looks like this:

JavaScript

When I do for example SnapshotIndicatorKeyValue .objects().first().snapshot, I can access the snapshotproperty.

But when I try to query it, it doesn’t work. For example:

JavaScript

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.

Advertisement

Answer

In order to query the snapshot property directly through mongoengine, you can reference the related snapshot object rather than the snapshot_id in your SnapshotIndicatorKeyValue document definition.

An amended model using a Reference field would be like this:

JavaScript

You would sucessively save an instance of Snapshot and an instance of SnapshotIndicatorKeyValue like this:

JavaScript

You can then refer to any of the snapshot‘s properties through:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement