I am trying to build a webapp with flask and mongoengine, but get stuck with the following problem.
Assume there is a document with JSON structure like this:
"user": {
"value": "username",
[...]
},
"entities": [
{
"key": "foo",
"value": "123"
},
"key": "bar",
"value": "456"
},
[...]
]
1) First I want to get the whole document from user "username", I tried:
userdata = models.User.objects(user__match = {"value": "username"})
but this return an empty doc. I also tried something like this:
userdata = models.User.objects(user__contains = "username")
But then I got:
AttributeError: 'str' object has no attribute 'get'
I read the docs, and sneaked around but found nothing helpful.
2)
When the document got (finally) from the DB, I need to catch all the value
s from the entities
for displaying that within an jinja2 template, but have no clue how to managed that.
This is (part of) the model:
class Username(EmbeddedDocument):
value = StringField(
primary_key = True,
unique = True)
created = DateTimeField(
require = True,
default = datetime.utcnow())
class Entities(EmbeddedDocument):
etype = StringField(
require = True,
choices = ENTITYTYPES)
key = StringField(
require = True,
choices = ENTITIES)
value = StringField(
require = True)
modiefied = DateTimeField(
require = True,
default = datetime.utcnow())
class User(Document):
user = EmbeddedDocumentField(
Username)
entities = ListField(
GenericEmbeddedDocumentField(Entities))
As mentioned from @Paul I tried some queries:
userdata = models.User.objects.get(entities={"key": "foo"})
Result: AttributeError: 'dict' object has no attribute 'to_mongo'
userdata = models.User.objects(entities={"key": "foo"})
Result: AttributeError: 'dict' object has no attribute 'to_mongo'
userdata = models.User.objects(user__entities = {"key": "foo"})
Result: mongoengine.errors.InvalidQueryError: Cannot resolve field "user"
userdata = models.User.objects.get(entities={"key": "foo"})
Result: AttributeError: 'dict' object has no attribute 'to_mongo'
userdata = models.User.objects(__raw__={"key": "foo"})
Result: []
userdata = models.User.objects(key='foo')
Result: mongoengine.errors.InvalidQueryError: Cannot resolve field "key"