-1

I am saving datetime and temperature values into a database and I am trying to get the last temperature and datetime value.

I tried using the code described in the link below:

How to get last record

And wrote this:

    query1 = db.session.query.order_by(temperaturelog.dTime.desc()).first()
    query2 = db.session.query.order_by(temperaturelog.Temperature.desc()).first()
    data.append(query1)
    data.append(query2)
    return data

However, I got errors such as:

NameError: name 'session' is not defined

Do I need to replace 'session' with something else? I tried using the variable used in the creation of the SQLAlchemy(app) and tried replacing it with my class name for the database which is temperaturelog.

All help appreciated,

Thanks.

  • You should edit your question to include the full traceback you receive. This will help to pinpoint the exact line of code causing the error. From the snippet you've provided, there doesn't seem to be anything that would cause the NameError so it must be somewhere else. – Matt Healy Mar 06 '18 at 22:27

1 Answers1

0

Firstly it's impossible to see where your NameError is coming from. In your example, you call session as an attribute of an object called db. If session doesn't exist in this context, it would throw an AttributeError, not NameError. The NameError is most likely coming from calling session in your module somewhere in an unqualified manner, before it has been defined.

Second is that your queries are different to the ones in the linked question in that you are not querying any object.

In Flask-SQLAlchemy, you can query on an object that is attached to a session upon the model itself. For example, if I have a class called Temperature and it is a Flask-SQLAlchemy instrumented object, you can query the class directly, e.g. Temperature.query.all(). The table that needs to be queried can then be inferred from the Temperature object's __tablename__ attribute.

In your example you appear to be querying on the session, which is fine but session.query isn't specific to any model. In this case you need to call session.query and pass it the model that represents the table that you want it to get the data from, e.g. session.query(Temperature).all() is a valid query.

SuperShoot
  • 9,880
  • 2
  • 38
  • 55