views:

43

answers:

2

Any pointers on how I can update the data for a model on each access?

If I have code that accesses a Person object like so: p = Person.objects.get(username='darkpixel')

I would like to fire off my own process to check an external site and possibly update the Person model before returning it.

I'm hesitant to override the get method. Is there a better way?

A: 

Turn the fields on the model into properties.

Ignacio Vazquez-Abrams
Is there a way to do it without having to change existing code that relies on (using your linked example) Person.first_name?The result I'm trying to get is to access data from my database-backed model, but occasionally check for updates on a Person from a remote web service.
Aaron C. de Bruyn
Properties usually don't require changing existing code, so I'm not sure what you're asking here...
Ignacio Vazquez-Abrams
A: 

That code definitely belongs in your Manager. I wouldn't override get, but I would create a function named get_and_resync to do the job for you.

Gattster
That's the direction I've headed with my prototype, and it seems to work well--I just need to make sure that all the projects that import my app occasionally call get_and_resync... The other option I'm thinking about is not worrying about projects calling get_and_resync, but instead have a manage.py command that slowly trawls through the DB and updates things as necessary...
Aaron C. de Bruyn
After doing a bit more digging, I stumbled across something interesting with Managers that I didn't know about. If you create a get_query_set function, you define the initial queryset used for looking up data via Person.objects.all, or Person.objects.get. This makes it easy to intercept and update objects before they are returned.
Aaron C. de Bruyn