Update a MongoEngine document using a python dict?

前端 未结 6 1016
我在风中等你
我在风中等你 2021-02-05 18:24

Is it possible to update a MongoEngine document using a python dict?

For example:

class Pets(EmbeddedDocument):
    name = StringField()

class Person(Do         


        
6条回答
  •  故里飘歌
    2021-02-05 19:04

    Pretty late to the game here, but FWIW, MongoEngine has a build in solution for this.

    Regardless if you want to create or update you can do the following:

    class Pets(EmbeddedDocument):
        name = StringField()
    
    class Person(Document):
        name = StringField()
        address = StringField()
        pets = ListField(EmbeddedDocumentField(Pets))
    
    p = Person(**{
        "name": "Hank",
        "address": "Far away",
        "pets": [{"name": "Scooter"}]
    })
    p.save()
    

    Only difference for update is you need to stick in an id. That way mongoengine won't duplicate a doc with an existing id and update it instead.

提交回复
热议问题