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 Model.save(models) 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’)

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

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

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

@with_transaction()
def test_default_save_all(self):
    Test = Pool().get(u'test.default')
    Test.save([Test(), Test()])
    tests = Test.search([])
    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: https://tryton-readthedocs.readthedocs.io/projects/server/en/latest/topics/models/fields_default_value.html

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.