flask-mongoengine AttributeError:'BaseQuerySet'对象没有属性'service_name'

时间:2018-06-12 09:10:25

标签: flask mongoengine flask-mongoengine

我的代码:

models.py

from flask_mongoengine import MongoEngine, QuerySet
import datetime

db = MongoEngine()

class Service(db.Document):
    service_name = db.StringField(max_length=50, required=True)
    date_created = db.DateTimeField(default=datetime.datetime.utcnow)
    meta = {
        'ordering': ['-date_created'], 'strict' : False
    }

class Organisation(db.Document):
    org_name = db.StringField(max_length=50, required = True)
    service = db.ReferenceField(Service, reverse_delete_rule='CASCADE', required=True)
    date_created = db.DateTimeField(default=datetime.datetime.utcnow)
    meta = {
        'ordering': ['-date_created'], 'strict' : False
    }

API(routes.py)

@service.route('/services/<name>', methods=['GET'])

def get_one_service(name):
    s = Service.objects(service_name=name)  
    if s:
        output = {'service_name' : s.service_name}
    else:
        output = "No such name"
    return jsonify({'result' : output})

get_one_service()方法返回上述错误。根据文档,这是正确的。

1 个答案:

答案 0 :(得分:0)

get_one_service函数中,s不是Service个实例,但文档中的查询集(this example可能会更清晰)

您可以通过以下操作访问Service的单个实例:

try
    s = Service.objects.get(service_name=name) 
    output = {'service_name' : s.service_name}
except Service.DoesNotExist:
    output = 'no such name'

但是,由于service_name字段在您的模型中不是唯一的,如果有两个文档具有相同的MultipleObjectsReturned,则可能会出现service_name异常。

或者,您可以查看s是否包含多个Service并执行相应操作。