Search code examples
flaskmongoengineflask-mongoengine

flask-mongoengine AttributeError: 'BaseQuerySet' object has no attribute 'service_name'


My Code:

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})

The get_one_service() method returns the above mentioned error. As per the documentation, this is correct.


Solution

  • In your get_one_service function, s is not a Service instance but a queryset (this example from the documentation might make it clearer)

    You can access a single instance of Service by doing something like:

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

    Though, since the service_name field is not unique in your model, you may get a MultipleObjectsReturned exception if there's two documents with the same service_name.

    Alternatively, you can see if s contains multiple Services and act accordingly.