Curiosity: how would I go about implementing a refresh() method on Model?
See original GitHub issueHere’s the scoop:
The project I’m working on creates the scenario where I have local variables holding instances of a variety of Models. Changes to some have side-effects on the others (intentional ones, via signals). Right now I’m using the following to “refresh” a model instance when I want to ensure the data is up-to-date:
instance = Model.get(Model.something = something)
# ...
# .. do work
# ...
# .. need to "refresh"
instance = Model.get(Model.id == instance.id)
# .. continue
I don’t mind the additional get, but I thought it might be fun to implement a refresh()
method on my base Model subclass. At my first crack, I caught myself trying this boneheaded implementation:
def refresh(self):
self = self.__class__.get(self.__class__.id == self.id)
Obviously that’s stupid. I don’t want to change self
. Anybody holding reference to that object won’t see the updates, as far as I can tell. There might be a nuance I’m missing in the Python runtime, but I’m pretty sure it wouldn’t work.
Have any ideas as to what I could try? I’d be glad to write it in such a way that it could make a PR to the project, if you think it’ll be useful for the general audience.
Issue Analytics
- State:
- Created 8 years ago
- Comments:6 (4 by maintainers)
Top GitHub Comments
I think something like this should be nice, but I in fact just wrote it now and haven’t yet tested enough. This works «in place» by loading another instance of the same class and copying all its fields. Seems to work as planned, but I am pretty sure there are some unwanted side effects somewhere. Maybe somebody has a better implementation?
If you want to get into a really hairy territory, you could go so far as to write some kind of code that takes in the remote updated version and merges it with the local object, and if it’s trying to clobber a locally-dirty field, raise some kind of exception, etc, but then again this is becoming more not-very-Pythonic the more we explore the possibilities.