Ing
Ing

Reputation: 611

How to search res.partner records in Odoo 14

I want to add check on field 'Email' in res.partner when confirming sale order.

class SaleOrderExtend(models.Model):
    _inherit = 'sale.order'

    def action_confirm(self):
        partner = self.env['res.partner'].search(['partner_id', '=', self.partner_id])
        if partner.email == '':
            raise UserError(_("""Email is empty ."""))
    ....

but I got this error : The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 639, in _handle_exception
    return super(JsonRequest, self)._handle_exception(exception)
  File "/usr/lib/python3/dist-packages/odoo/http.py", line 315, in _handle_exception
    raise exception.with_traceback(None) from new_cause
IndexError: tuple index out of range

What's wrong please? Thanks.

Upvotes: 2

Views: 2674

Answers (2)

kamalpreet
kamalpreet

Reputation: 101

class SaleOrderExtend(models.Model):
   _inherit = 'sale.order'

   def action_confirm(self):
     if not self.partner_id.email or not self.partner_id.email.strip():
        raise UserError(_("""Email is empty ."""))
   ....

Upvotes: 1

CZoellner
CZoellner

Reputation: 14768

Firstly your search domain is wrong. It should be a list of special logical operators as strings and triplets (tuples or lists with 3 values).

I won't describe the domain syntax in detail now, because your code only has a simple mistake: your triplet should be in a list:

self.env['res.partner'].search([('partner_id', '=', self.partner_id)])
# or as lists in list
self.env['res.partner'].search([['partner_id', '=', self.partner_id]])

Secondly this search won't work, because there is no partner_id field in res.partner model and self.partner_id is a recordset not an ID, which you will need on searches on many2one fields. In the end what you need is to find the partner of that order you're confirming.

You don't need to search it, because it's already an attribute of self in this case.

    def action_confirm(self):
        if not self.partner_id.email:
            raise UserError(_("""Email is empty ."""))

Some optimization hints: email addresses can be empty or even only spaces, because it's just a simple string/char field. So try to take that into consideration aswell:

    def action_confirm(self):
        if not self.partner_id.email or not self.partner_id.email.strip():
            raise UserError(_("""Email is empty ."""))

And one more: It is possible to confirm more than one order at once, so try to consider that, too:

    def action_confirm(self):
        not_valid_orders = self.filtered(
            lambda o: not o.partner_id.email or not o.partner_id.email.strip())
        if not_valid_orders:
            raise UserError(
                _("""Some orders have partners without email address"""))

Upvotes: 1

Related Questions