Question

There is something I didn't notice until today.

record3 = Record(record_date=today.date(), user=user.key)
record3.put()
record3.record_date=tomorrow.date()
record = Record.query().get()

I create an entity and store it in the data store. Then I change its date, but don't save it via Put(). And when I query for it from datastore, I was expecting the date to show today's date, however it already shows tomorrow's date.

Is put() using some sort of after update hook, to always update the entities after a put() has been taken place? It is quite different than traditional ORM with SQL.

UPDATE: To prove my point or for sake of missing something:

def test_get_or_insert_updates_after_get(self):
        user = self.signup()
        today = datetime.datetime.strptime('20140405', '%Y%m%d')
        tomorrow = datetime.datetime.strptime('20140406', '%Y%m%d')
        record3 = Record(record_date=today.date(), user=user.key)
        record3.put()
        record3.record_date=tomorrow.date()
        record = Record.query().get()
        self.assertEqual(today.date(), record.record_date)

This unit test is failing. But why?

AssertionError: datetime.date(2014, 4, 5) != datetime.date(2014, 4, 6)

Solution: I had a bit of difficulty to understand Daniel's solution at first. This is the code sample:

ctx = ndb.get_context()
ctx.clear_cache()
record = Record.query().get()
Was it helpful?

Solution

You're being misled by the ndb in-context cache:

When an NDB function writes to the Datastore, it also writes to the in-context cache. When an NDB function reads an entity, it checks the in-context cache first.

Since you're doing a direct .get(), rather than a query, ndb will use the in-context cache and return the same object. It doesn't get a new instance from the datastore, so you will see that object's local modifications. You can verify this with:

self.assertTrue(record is record3)

Alternatively, use a query, or set the context specifically to disable the cache as explained at the link above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top