This question has been flagged
2 Replies
14522 Views

Is there a way to count the number of records in a one2many field? 
 

Avatar
Discard

@abdullah What exactly you want to achieve by knowing the count of one2many fields?

Author

I have two classes : (batches) & (batches.registrations) In (batches), I have a one2many field called "student_registrations" pointing to (batches.registrations) and showing the student registrations for this batch. However, I can only register 18 to 20 students as per the capacity of the classroom. I need to know how to limit the number of student registrations per batch in the one2many field once the registrations reach 18 or 20.

Related topic link https://www.odoo.com/forum/help-1/question/how-set-limit-for-number-records-of-x2many-6627 https://www.odoo.com/forum/help-1/question/how-to-limit-the-total-number-values-for-a-one2many-field-49700

Best Answer

use len like.. 
 

so = self.pool.get('sale.order').browse(cr, uid, id)
count = len(so.order_line)

 

hope it helps

edit after comment:

also need to check if there is an object like:
count = so.order_line and len(so.order_line) or 0

Avatar
Discard
Author

I tried this but I get this error: object of type 'bool' has no len()

Best Answer

Try using _constraints.

    def _check_batch_limit(self, cursor, user, ids, context=None):
        for record in self.browse(cursor, user, ids, context=context):
            //limit is set as 18 or 20
            if len(record.student_registrations) > record.limit:
                return False
        return True

    _constraints = [
        (_check_batch_limit, 'Error:Limit reached.', ['student_registrations']),
    ]

Avatar
Discard
Author

I am sorry for my question... but does this code get the limit value from a field in the form?

Author

This code does not work. Why did you accept the answer?

@Abdullah, No one will provide you exact code changes for your problem. We can only provide how this can be achieved. and VOTE is different from ACCEPT.

yes. I obtained the limit value from "LIMIT" field at FORM view.

Author

Sorry for my previous comments. You were absolutely right from the start. Thanks you Atchuthan.