AttributeError:“类”对象没有属性“ update_one”

时间:2019-02-17 16:26:53

标签: python flask mongoengine

我在使用update_one方法删除和更新时遇到问题。似乎该方法尚未在mongoengine中实现。我的目标是从ListField中删除Student字段。在示例代码中,我的模型显示了数据库模式,而我的视图则显示了应用程序的路由。我想要一个阻止我从StudentYear类访问方法(update_one)的示例。我不知道如何格式化堆栈溢出,所以在此先对不起。

ListField(ReferenceField('Student'))。我一直在得到错误AttributeError:'SchoolYear'对象没有属性'update_one',并且我一直在寻找一种解决方案,该解决方案可以解决我最近遇到的这两个链接,但是当我自己尝试时,它不起作用。

MongoEngine - Pull a reference from a ListField, by id

https://github.com/mongomock/mongomock/issues/458

以下链接上的第25页显示使用update_one方法删除和添加 https://media.readthedocs.org/pdf/mongoengine-odm/stable/mongoengine-odm.pdf

requiredfile.txt
Click==7.0
Flask==1.0.2
Flask-MongoAlchemy==0.7.2
flask-mongoengine==0.9.5
Flask-WTF==0.14.2
itsdangerous==1.1.0
Jinja2==2.10
MarkupSafe==1.1.0
mongoengine==0.16.3
mongomock==3.14.0
pymongo==3.7.2
sentinels==1.0.0
six==1.12.0
Werkzeug==0.14.1
WTForms==2.2.1

模型

from mongoengine import *

from mongoengine.fields import *

class Student(Document):

    FirstName  = StringField(default='')
    LastName   = StringField(default='')
    listNumber = IntField(default=0)
class SchoolYear(Document):

    year = IntField(required=True,min_value=1871, max_value=2020)
    students = ListField(ReferenceField('Student', required=True, reverse_delete_rule=CASCADE))

查看

from flask import Blueprint, jsonify, request,Response

from models import  Student, SchoolYear

from bson import json_util

@app.route('/location/', methods=['POST'])

def remove_student():

    encodedString = request.get_json()
    FirstName = str(encodedString['FirstName'])
    LastName = str(encodedString['LastName'])
    year = int(encodedString['year'])
    students_year = SchoolYear.objects(year=year).get()
    for student in students_year.students:
        if(str(student['FirstName']) == FirstName and str(student['LastName']) == LastName):

            students_year.update_one(pull__students=student)
    return jsonify({'result': 10})

1 个答案:

答案 0 :(得分:0)

update/update_one都可以在查询集的

上使用
SchoolYear.objects(year=year).update_one(pull__students=student)

但是在文档实例上只有update可用,因此您应该像下面这样简单地使用.update而不是.update_one

students_year = SchoolYear.objects(year=year).get()
students_year.update(pull__students=student)