gpt4 book ai didi

flask - 蒙戈引擎 : How to update specific fields of an existing document?

转载 作者:行者123 更新时间:2023-12-02 05:23:27 26 4
gpt4 key购买 nike

我有一个现有的 mongo 文档,该文档已通过 REST API 公开。 API 请求将包含文档中的某些字段,如果该字段为空,则需要使用新值更新这些字段或在其中插入新值。如何对现有 mongoengine 文档的字段执行更新?我正在使用 marshmallow-mongoengine 在 Flask 上进行序列化。

我面临的问题是,如果请求有效负载中缺少某个字段,则在使用剩余字段作为 kwargs 调用更新时会导致将缺少的字段设置为 None。如何仅更新或插入有效负载中给定的字段?

最佳答案

约瑟夫的回答是好的。但另一个答案不会有什么坏处啊!

这是我如何使用flask-mongoengine更新我的文档

实际代码:

Game.objects(id = _id).update(
set__kickoff = request_json.get('kickoff'),
set__gameid = request_json.get('gameid'),
set__home_team = request_json.get('home_team'),
set__away_team = request_json.get('away_team'),
set__home_win = request_json.get('home_win'),
set__draw = request_json.get('draw'),
set__away_win = request_json.get('away_win'),
set__sport = request_json.get('sport')
)

Game class :

import datetime
flask_mongoengine import BaseQuerySet, MongoEngine
db = MongoEngine()

class Game(db.Document):
kickoff = db.DateTimeField(required=True)
added_on = db.DateTimeField(default=datetime.datetime.utcnow)
gameid = db.FloatField(required=True)
home_team = db.StringField(required=True)
home_win = db.FloatField(required=True)
draw = db.FloatField(required=True)
away_win = db.FloatField(required=True)
away_team = db.StringField(required=True)
sport = db.StringField(required=True)
meta = {
'collection':'games',
'queryset_class': BaseQuerySet
}

PS:Python中的代码记得缩进

此外,我注意到您在问题中标记了棉花糖。这里是一个来自官方 git repo 的示例 here

First we need a Mongoengine Document:

import mongoengine as me

class Task(me.EmbeddedDocument):
content = me.StringField(required=True)
priority = me.IntField(default=1)


class User(me.Document):
name = me.StringField()
password = me.StringField(required=True)
email = me.StringField()
tasks = me.ListField(me.EmbeddedDocumentField(Task))

Great ! Now it's time for the Marshmallow Schema. To keep things DRY, we use marshmallow-mongoengine to do the mapping:

import marshmallow_mongoengine as ma

class UserSchema(ma.ModelSchema):
class Meta:
model = User

Finally it's time to use our schema to load/dump documents:First let's create a document

user_schema = UserSchema()
u, errors = user_schema.load({"name": "John Doe", "email":
"jdoe@example.com", "password": "123456","tasks": [{"content": "Find a
proper password"}]})
u.save()

If the document already exists, we can update it using update

u
u2, errors = user_schema.update(u, {"name": "Jacques Faite"})
>>> u2.name
"Jacques Faite"

关于flask - 蒙戈引擎 : How to update specific fields of an existing document?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51258463/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com