Reading list Switch to dark mode

    Database Population using ODOO CLI

    Updated 15 November 2023

    database-population-using-odoo-cli

    Odoo CLI supports Database Population.

    This article gives an overview of how we can work with the Database Population in Odoo as a developer.

    Before starting this tutorial, you should have a basic idea of CLI in Odoo. Besides, If you don’t have basic knowledge of Odoo CLI, read a beginner guide to Odoo CLI.

    Why do we need a Database Population in Odoo CLI?

    You can test your modules in the database by automatic data generation of the model’s records

    Before moving ahead, check out our Odoo development services & an extensive range of quality Odoo Apps.

    Start your headless eCommerce
    now.
    Find out More

    How does Database Population work in Odoo CLI?

    Syntax:-

    odoo-bin populate –-models product.category,product.template –-size small -d demo –-db_user odoo --db_password=webkul

    Output for upper command

    database-population-code
    populated-database-odoo

    Parameters:-

    – -models

    list of models for which the database should be filled.

    – -size(small | medium | large)

    The total number of the records to be created is depends on the model’s populate_size attribute

    The generated records content is specified by the _populate_factories() method of a given model.

    -d

    Name of the db

    –db_user

    Name of the DB User

    –db_password

    Password for the DB User

    Implement Features on a Given Model

    Define the following methods and attributes to populate a given model:-

    i) Model._populate_sizes

    The default population sizes are:

    Small: 10

    Medium: 100

    Large: 1000

    populate sizes are the number of records that _populate() should create.

    ii) Model._populate_dependencies

    Return the list of models which have to be populated before the current one.

    iii) Model._populate(size)

    Create records to populate this model.

    iv) Model._populate_factories()

    Generates a factory for the different fields of the model.

    factory is a generator of values (dict of field values).

    Factory skeleton:

    def generator(iterator, field_name, model_name):
        for counter, values in enumerate(iterator):
            # values.update(dict())
            yield values

    Note*: You have to define at least _populate() or _populate_factories() on the model to enable database population.

    Example:

    from odoo.tools import populate
    
    class WebkulModel(models.Model)
        _inherit = "webkul.some_model"
        _populate_sizes = {"small": 100, "medium": 2000, "large": 10000}
        _populate_dependencies = ["webkul.some_other_model"]
    
        def _populate_factories(self):
            # Record ids of previously populated models are accessible in the registry
            some_other_ids = self.env.registry.populated_models["webkul.some_other_model"]
    
            def get_some_field(values=None, random=None, **kwargs):
                """ Choose a value for some_field depending on other fields values.
    
                :param dict values:
                :param random: seeded :class:`random.Random` object
                """
                field_1 = values['field_1']
                if field_1 in [value2, value3]:
                    return random.choice(some_field_values)
                return False
    
            return [
                ("field_1", populate.randomize([value1, value2, value3])),
                ("field_2", populate.randomize([value_a, value_b], [0.5, 0.5])),
                ("some_other_id", populate.randomize(some_other_ids)),
                ("some_field", populate.compute(get_some_field, seed="some_field")),
                ('active', populate.cartesian([True, False])),
            ]
    
        def _populate(self, size):
            records = super()._populate(size)
    
            # If you want to update the generated records
            # E.g setting the parent-child relationships
            records.do_something()
    
            return records

    Population Tools

    Multiple population tools are available to easily create the needed data generators.

    i) odoo.tools.populate.cartesian(vals, weights=None, seed=False, formatter=<function format_str>, then=None)

    Return a factory for an iterator of values dicts that combines all vals for the field with the other field values in input.

    Parameters:

    • vals (list) – list in which a value will be chosen, depending on weights
    • weights (list) – list of probabilistic weights
    • seed – optional initialization of the random number generator
    • formatter (function) – (val, counter, values) –> formatted_value
    • then (function) – if defined, factory used when vals has been consumed.

    Returns: function of the form (iterator, field_name, model_name) -> values

    Return type: function (iterator, str, str) -> dict

    ii) odoo.tools.populate.compute(function, seed=None)

    Return a factory for an iterator of values dictionary (dicts) that computes the field value as a function (values, counter, random), where values are the other field value, counter is an integer, and random is a pseudo-random number generator.

    Parameters:

    • function (callable) – (values, counter, random) –> field_values
    • seed – optional initialization of the random number generator

    Returns: function of the form (iterator, field_name, model_name) -> values

    Return type: function (iterator, str, str) -> dict

    iii) odoo.tools.populate.constant(val, formatter=<function format_str>)

    Return a factory for an iterator of values dicts that sets the field to the given value in each input dict.

    Returns: function of the form (iterator, field_name, model_name) -> values

    Return type: function (iterator, str, str) -> dict

    iv) odoo.tools.populate.iterate(vals, weights=None, seed=False, formatter=<function format_str>, then=None).

    Return a factory for an iterator of values dicts that picks a value among vals for each input. Once all vals have been used once, resume as then or as a randomize generator.

    Parameters:

    • vals (list) – list in which a value will be chosen, depending on weights
    • weights (list) – list of probabilistic weights
    • seed – optional initialization of the random number generator
    • formatter (function) – (val, counter, values) –> formatted_value
    • then (function) – if defined, factory used when vals has been consumed.

    Returns: function of the form (iterator, field_name, model_name) -> values

    Return type: function (iterator, str, str) -> dict

    v) odoo.tools.populate.randint(a, b, seed=None)

    Return a factory for an iterator of values dicts that sets the field to a random integer between a and b included in each input dict.

    Parameters:

    • a (int) – minimal random value
    • b (int) – maximal random value
    • seed (int) –

    Returns: function of the form (iterator, field_name, model_name) -> values

    Return type: function (iterator, str, str) -> dict

    vi) odoo.tools.populate.randomize(vals, weights=None, seed=False, formatter=<function format_str>, counter_offset=0)

    Return a factory for an iterator of values dicts with pseudo-randomly chosen values (among vals) for a field.

    Parameters:

    • vals (list) – list in which a value will be chosen, depending on weights
    • weights (list) – list of probabilistic weights
    • seed – optional initialization of the random number generator
    • formatter (function) – (val, counter, values) –> formatted_value
    • counter_offset (int) –

    Returns: function of the form (iterator, field_name, model_name) -> values

    Return type: function (iterator, str, str) -> dict

    NEED HELP?

    Hope you find the guide helpful! Please feel free to share your feedback in the comments below.

    If you still have any issues/queries regarding the same, please raise a ticket at the UV Desk.

    For any doubt, contact us at our support mail.

    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home