Skip to Content
Menú
This question has been flagged
2 Respostes
1064 Vistes

Hello !

I've created a custom List Field.

I know how to add values one by one but how can I add several values at once ?


Thanks !

Avatar
Descartar
Autor Best Answer

Thanks a lot, much appreciated. I was hoping for a solution without coding but apparently it cannot be done.

Avatar
Descartar
Best Answer

Hi,

Here's how you can add multiple values at once to a many2many or one2many field:


Suppose you have a many2many field custom_list_field on a model, and you want to add several records to it at once.

Example Code python:


def add_multiple_values(self):

    # Example: Getting the IDs of the records you want to add

    new_values_ids = [1, 2, 3]  # Replace with actual record IDs you want to add


    # Use the `[(6, 0, [ids])]` command to add all values at once

    self.custom_list_field = [(6, 0, new_values_ids)]


Explanation:


    6: Refers to the command to replace the existing records with the list of IDs you provide.

    0: It is required by the syntax but not used here.

    new_values_ids: The list of IDs that you want to add to the many2many field.


Example for one2many Field:


In the case of an one2many field, the approach is similar but with a different syntax since you may need to provide more details like creating new records.

Example Code python:


def add_multiple_one2many_values(self):

    # Example: Prepare data for creating multiple records

    new_records = [

        (0, 0, {'field_1': 'value_1', 'field_2': 'value_2'}),

        (0, 0, {'field_1': 'value_3', 'field_2': 'value_4'})

    ]


    # Add new records to the one2many field

    self.one2many_field = new_records


Thanks

Avatar
Descartar