Why don't some operators work properly with record sets in Odoo?

I did some tests:

>>> empty_recordset = self.env['res.users']                                 # empty recordset
>>> not_empty_recordset = self.env['res.users'].search([('id', '=', 1)])    # recordset with one record

>>> empty_recordset is False
False

>>> empty_recordset is None
False

>>> empty_recordset == False
False

>>> empty_recordset == True
False

>>> bool(empty_recordset)
False

>>> not empty_recordset
True

>>> if empty_recordset:           # it is treated as False
...     print('hello')
... 

>>> bool(not_empty_recordset)
True

>>> if not_empty_recordset:
...     print('hello')
... 
hello

>>> not not_empty_recordset
False
  • When typing records with, bool()it returns Trueor False.
  • With operators ifand the notresult is also expected.
  • But when it is used with operators is, ==, !=, the result is not expected.

What's happening? Is a recordset processed as a boolean with ifand instructions only not? Are the other operators not overloaded?

+4
source share
2 answers

This is the way __nonzero__:

bool(); False True 0 1. , len(), , , , len(), (), .

odoo/odoo/models.py:

Odoo 10 :

def __nonzero__(self):
    """ Test whether ``self`` is nonempty. """
    return bool(getattr(self, '_ids', True))
+2

, . python

      if object: 
       #  is turned to. 
      if object.__nonzero__():

      if object == value:
      #is turned to
      if object.__eq__(value):

:

      object + value
      # is converted go this
      object.__add__(value) 

.

, python .

+3

Source: https://habr.com/ru/post/1690626/


All Articles