Mongoengine, retriving only some of a MapField

十年热恋 提交于 2019-12-06 09:27:33

I see there is a ticket for this: https://github.com/hmarr/mongoengine/issues/508

Works for me heres an example test case:

def test_only_with_mapfields(self):

    class BlogPost(Document):
        content = StringField()
        author = MapField(field=StringField())

    BlogPost.drop_collection()

    post = BlogPost(content='Had a good coffee today...', 
                    author={'name': "Ross", "age": "20"}).save()

    obj = BlogPost.objects.only('author__name',).get()

    self.assertEquals(obj.author['name'], "Ross")
    self.assertEquals(obj.author.get("age", None), None)

Try this:

query = BlogPost.objects({your: query})
if name:
    query = query.only('author__'+name)
else:
    query = query.only('author')

As always, Ross Really Thanks a lot!!!!!!!!!

I found my fault.. that is.. I used 'only' twice..

For example,

BlogPost.objects.only('author').only('author__name') 

something like this..

I spent a whole day finding out what is wrong with Mongoengine..

so.. my dumb conclusion was...

BlogPost.objects()._collection.find_one(~~ filtering query ~~, {'author.'+ name:1})

something like this..

but as you know it's a just raw data not a mongoengine query..

after this code, I cannot run any mongoengine methods...

Anyway..

In my case, I should have to query depending on some conditions.

so it will be great that 'only' method overwrites 'only' methods written before.. In my humble opinion.

I hope this feature would be integrated with next version..

Right now, I have to code duplicate code.. for example..

not this code...

query = BlogPost.objects()
query( query~~).only('author')
if name:
    query = query.only('author__'+name)

this code

query = BlogPost.objects()
query( query~~).only('author')
if name:
    query = BlogPost.objects().only('author__'+name)

so.. I think.. the second one looks dirtier than first one.

of course, the first code shows you all all data using "only('author')" not "only('author__name')

Thanks A LOT!!!!!!!!!

Ross, you saved me!!! Thanks.. (I thought Mongoengine could not simply do those queries.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!