Jaysinh
Jaysinh

Reputation: 57

Using 'len()' in order of search function

I want to apply the len(one2many_field) in Search method of ORM. Like this search(..,order = "len(one2many_field)",..) .I want to order the result by finding total number of their children. The one2many field is in the relation to the same table. Presently I am not able to use len() in order.

Example :

 id    name    parent_id
  1     A       - 
  2     B       1 
  3     C       1 
  4     D       - 
  5     E       4

Result :

A
D

Upvotes: 0

Views: 221

Answers (2)

Adrian Merrall
Adrian Merrall

Reputation: 2499

If I understand correctly, you want to be able to do a query such as show me all sales orders that have three or more order lines (for example). I am using sale order and sale order lines as the example here but just substitute whatever parent/child models you are working with.

  1. Extend sale order and add a functional field that simply returns the count of the sale order lines one2many field.
  2. Make it a triggered stored field. Have a look at how the amounts are stored on sale order for an example of this. You can pretty much copy and paste it but change the field names.
  3. Use if in your search as:

    sale_order_model.search(cr, uid, [('my_count_field', '>=', 3)], context = context)

The only tricky part here is getting the store triggers right but the amounts on sale order are a perfect example for you.

Upvotes: 1

CZoellner
CZoellner

Reputation: 14778

i don't thinks it's possible to use len() on the order parameter of the orm search method, because the parameter has to be a comma-separated list of valid field names. for reference, the openerp code for construction of a order by clause (for queries):

def _generate_order_by(self, order_spec, query):
        """
        Attempt to consruct an appropriate ORDER BY clause based on order_spec, which must be
        a comma-separated list of valid field names, optionally followed by an ASC or DESC direction.

        :raise" except_orm in case order_spec is malformed
        """
...

you will find this under: openerp-server.openerp.osv.orm.BaseModel

Upvotes: 0

Related Questions