使用mongoengine查询复杂的JSON模式

时间:2016-02-20 14:00:42

标签: python json flask jinja2 mongoengine

我正在尝试使用flask和mongoengine构建一个webapp,但是遇到了以下问题。

假设有一个JSON结构的文档,如下所示:

"user": {
  "value": "username",
  [...]
},
"entities": [
  {
    "key": "foo",
    "value": "123"
  }, 
    "key": "bar",
    "value": "456"
  },
  [...]
]

1) 首先,我想从用户“用户名”获取整个文档,我试过:

userdata = models.User.objects(user__match = {"value": "username"})

但这会返回一个空文档。我也试过这样的事情:

userdata = models.User.objects(user__contains = "username")

但后来我得到了: AttributeError: 'str' object has no attribute 'get'

我阅读了文档,然后偷偷溜走,但没有发现任何帮助。

2) 当文档从数据库中获取(最终)时,我需要捕获value中的所有entities以在jinja2模板中显示它,但不知道如何管理它。

这是(模型的一部分):

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))

正如@Paul所提到的,我尝试了一些问题:

userdata = models.User.objects.get(entities={"key": "foo"})  

结果:AttributeError: 'dict' object has no attribute 'to_mongo'

userdata = models.User.objects(entities={"key": "foo"})  

结果:AttributeError: 'dict' object has no attribute 'to_mongo'

userdata = models.User.objects(user__entities = {"key": "foo"})  

结果:mongoengine.errors.InvalidQueryError: Cannot resolve field "user"

userdata = models.User.objects.get(entities={"key": "foo"})  

结果:AttributeError: 'dict' object has no attribute 'to_mongo'

userdata = models.User.objects(__raw__={"key": "foo"})  

结果:[]

userdata = models.User.objects(key='foo')  

结果:mongoengine.errors.InvalidQueryError: Cannot resolve field "key"

2 个答案:

答案 0 :(得分:1)

在进一步搜索时,我遇到了this Questionthis

把它们放在一起为我的第一个问题提出了这个答案:
data = models.User.objects(__raw__ = { 'user.value': 'username' })

所以我从用户那里获得数据。要在jinja2中对其进行排序,我发现了Questionthat,所以我来到了这个模板:

{% for dict_item in data %}
  {% for item in dict_item['entities'] %}
    <h1>Key: {{item['key']}}</h1>
    <h2>Value: {{item['value']}}</h2>
  {% endfor %}
{% endfor %}

仅供参考:如果需要在shell中打印mongoengine查询,请使用:

from bson import json_util
objects = models.User.objects.all()
json_util.dumps(objects._collection_obj.find(objects._query))

答案 1 :(得分:0)

我是对的,那个模型User有一个字段user,那个字段是一个字典? 如果你试试这个怎么办:

userdata = models.User.objects.get(user={"value": "username"}) # will return one
userdata = models.User.objects(user={"value": "username"})     # will return multiple

或者这个:

userdata = models.User.objects(user__user = {"value": "username"})