Ir al contenido
Menú
Se marcó esta pregunta
1 Responder
20603 Vistas

Two snippets to get the same list of ids:

id_list = [];
for obj in self.browse(cr, uid, ids, context=None):
    for o2m in obj.o2m_field_ids:
        id_list.append(o2m.id);

or:

o2m_obj = self.pool.get('o2m.object');
id_list = o2m_obj.search(cr, uid, [('m2o_field_id','in',ids)]);

Which is faster? 'better'? cleaner? more pythonic? more readable? better style?

EDIT:

An actual example would be to collect all tasks of one or more projects:

I could loop over the projects and collect the tasks (browse the projects), or search for all tasks that belong to the given projects (search in tasks).

I think this can make differences in performance, etc.

 

Thanks.

Avatar
Descartar
Mejor respuesta

Well, I don't think you should use both for the same purposes. If you want just a list of ids to push around, use the search. It will always give you back just ids in a list. If you want to do something with the fields of these records as well, you use the browse. 

 

The top example is very counter-intuitive as well. You already have the ids; self.browse(cr, uid, ids, context=None), so why bother going trough the objects to find that the result of the browse and for-loop is the exact same as the ids you are passing already?

So for example if you need all the partners that are customers:

partner_obj = self.pool.get('res.partner')

partner_ids = partner_obj.search(cr, uid, [('customer','=',True)])

and if you need more information of those partners, feed that list into a browse:

partners = partner_obj.browse(cr, uid, partner_ids)

for partner in partners:

    if partner.active:

         print "It is active"

Avatar
Descartar
Autor

Thx for the reply. Of course often you can't choose between both options. But I#m not sure you got my first example right. Its not just returning the already avaible ids. I've updated my question with an example.

Aha, now I see. Well in that case, part of my point still stands. If you need just the ids and no more information, the simple search should do the trick. If you know you will be using other information of either project or task (as reference to your example) you will need the browse. Speedwise is should not make much of a difference, unless you are talking about millions of records simultaneously.

Publicaciones relacionadas Respuestas Vistas Actividad
8
jul 24
16063
2
sept 20
36659
1
ago 17
8741
2
dic 23
19778
2
mar 15
5513