Python – Peewee ORM gets updated database data

Peewee ORM gets updated database data… here is a solution to the problem.

Peewee ORM gets updated database data

I have a basic conceptual question about using ORMs (specifically Peewee) on dynamically changing relational data.

Peewee maps information from a database to Python objects for ease of use.

My understanding is that queries produce Python objects at query time. Then should the properties of the object generated by the database data (in my case via another thread) somehow be changed now obsolete, right?

My core problem is that my application is structurally very asynchronous – the web application provides the front end (via Flask), the hardware sensors input data, and the running daemon determines what action to take based on the contents of my database. As a result, I had to constantly manually re-query so that my Python objects correctly represented the data in the database, for example:

name = 'obj_name'
instance = Model.select().where(Model.name = name)
#time passes, need to refresh
instance = Model.get(Model.id == instance.id)

Is there any way to make it more elegant?

Ideally, I would automatically requery the database every time I accessed a Peewee object.

Or I can add a refresh() method that updates the object, for example:

instance = instance.refresh()

Any suggestions?

What is the most concise way to use an ORM in this case?

Solution

So you have long-lived Python objects in one thread while another thread is updating the database? Requerying is the best thing you can do with an ActiveRecord ORM like Peewee.

def refresh(self):
    return type(self).get_by_id(self._pk)

Related Problems and Solutions