Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>One way is to add a setter for the state. It's just a normal method, nothing special.</p> <pre><code>class Game(models.Model): # ... other code def set_state(self, newstate): if self.state != newstate: oldstate = self.state self.state = newstate if oldstate == 'S' and newstate == 'A': self.started = datetime.now() # create units, etc. </code></pre> <p><strong>Update:</strong> If you want this to be triggered <em>whenever</em> a change is made to a model instance, you can (<em>instead</em> of <code>set_state</code> above) use a <code>__setattr__</code> method in <code>Game</code> which is something like this:</p> <pre><code>def __setattr__(self, name, value): if name != "state": object.__setattr__(self, name, value) else: if self.state != value: oldstate = self.state object.__setattr__(self, name, value) # use base class setter if oldstate == 'S' and value == 'A': self.started = datetime.now() # create units, etc. </code></pre> <p>Note that you wouldn't especially find this in the Django docs, as it (<code>__setattr__</code>) is a standard Python feature, documented <a href="http://docs.python.org/reference/datamodel.html?highlight=__setattr__#object.__setattr__" rel="noreferrer">here</a>, and is not Django-specific.</p> <p>note: Don't know about versions of django older than 1.2, but this code using <code>__setattr__</code> won't work, it'll fail just after the second <code>if</code>, when trying to access <code>self.state</code>.</p> <p>I tried something similar, and I tried to fix this problem by forcing the initialization of <code>state</code> (first in <code>__init__</code> then ) in <code>__new__</code> but this will lead to nasty unexpected behaviour.</p> <p>I'm editing instead of commenting for obvious reasons, also: I'm not deleting this piece of code since maybe it could work with older (or future?) versions of django, and there may be another workaround to the <code>self.state</code> problem that i'm unaware of</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload