Note that there are some explanatory texts on larger screens.

plurals
  1. POOverwrite auto_now for unittest
    primarykey
    data
    text
    <p>I've defined some timestamps for events in the database as <code>auto_now_add</code>, as the information should be stored with it's timestamp the same time the event is stored.</p> <p>The description of the events is something like</p> <pre><code>class NewEvent(models.Model): ''' Individual event ''' name = models.CharField(max_length=100) quantity = models.FloatField(null=True) timestamp = models.DateTimeField(auto_now_add=True) </code></pre> <p>To test the module, I'm generating some information in the database in the <code>test.py</code> file, this way:</p> <pre><code> for event in EVENT_TYPES: time = datetime.datetime.now() - datetime.timedelta(days=1) for i in range(48): time = time.replace(hour=i / 2) NewEvent(name=event, timestamp=time, quantity=i).save() </code></pre> <p>I must generate events with its timestamp of yesterday (the module will then summarize them). The problem is that you can't overwrite the timestamp. The timestamp it's the one when the event it's produced, the <a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#datefield" rel="noreferrer">documentation</a> states that very clearly.</p> <p>So, how to generate data with appropiate timestamps for the testing? I've had several ideas:</p> <ul> <li>Maybe generate the database data in a different way, outside the Model classes. Where and how?</li> <li>Somehow define a different class or change the class to behave differently during test, something like</li> </ul> <p>_</p> <pre><code> if testing: timestamp = models.DateTimeField(auto_now_add=True) else: timestamp = models.DateTimeField(auto_now_add=False) </code></pre> <p>Or maybe there's an even easier way to do this... Any ideas?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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