Default_field (with random data) and batch save. Expected behaviour?

I have a get_default which generates random data (per design), it works ok when models are saved one by one.
If I create a bunch of instances of the model and save them all at once with I get the same default value for all of them. Is this the expected behavior?
I am guessing that the get_default is only called once for all the models instead of one time for each model. I can see how this can save time in some scenarios but it’s not what I expected.
I am working on 4.8 (not default)
In the following test test_default_save_all fails. That was an unexpected behavior for me.

class TestDefault(ModelSQL):
doc = u’Test’
name = u’test.default’
default = fields.Integer(u’Default’)

def default_default(cls):
    return random.randint(1L, 1024L)

class TestCase(ModuleTestCase):
doc = u’Test’
module = u’scratch’

def test_default_save_one_at_time(self):
    Test = Pool().get(u'test.default')
    test1 = Test()
    test2 = Test()
    tests =[])
    return self.assertFalse(test1.default == test2.default)

def test_default_save_all(self):
    Test = Pool().get(u'test.default')[Test(), Test()])
    tests =[])
    return self.assertFalse(first(tests).default == second(tests).default)

(note: there may be some code like first and second which seems estrange but does not affect the test, I write most of my code in hy and this is the python translation)

As a work around I ended up setting the default fields before calling save.

Yes it is. We should probably document it on:

Yes this is for performance reason (server and client side). But also when a new column is added we need to have a single value to use in the update query.

The best is probably to override ModelStorage.create method and fill the missing value like it is done in ir.session.

This topic was automatically closed 12 hours after the last reply. New replies are no longer allowed.