Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
2 Trả lời
6932 Lượt xem

In our lead model/forms we have two addresses and would like to automatically compute the driving distance between them and display/store it in another field. I've done this in Python before by calling Google's Distance Matrix API (outside of Odoo).

My question is, what is the easiest way to integrate a bit of Python code to compute a field via an API? Possibly a trigger when the lead/opportunity is updated? If so, how can that be done?

Thank you!

Ảnh đại diện
Huỷ bỏ
Tác giả Câu trả lời hay nhất

Thanks Mai for your comment which put me on the right track...

I ended up creating a module that extends the crm.lead model. Here's a simplified version:

# -*- coding: utf-8 -*-
from odoo import models, fields, api
class DistanceLead(models.Model):
    _inherit = 'crm.lead'
    address1 = fields.Char(string='Start Address')
    address2 = fields.Char(string='End Address')
    distance = fields.Float(string='Driving Distance', compute='_compute_distance')
    
    
    @staticmethod
    def get_distance_km(start_addr, end_addr):
        if start_addr=='' or end_addr=='':
            return 0
        import googlemaps
        client = googlemaps.Client("YOUR-API-KEY")
        try:
            matrix = client.distance_matrix([start_addr], [end_addr])
            distance_km = matrix['rows'][0]['elements'][0]['distance']['value'] / 1000.00
            return distance_km
        except:
            return 0


    @api.depends('address1', 'address2')
    def _compute_distance(self):
        self.distance = DistanceLead.get_distance_km(self.address1, self.address2)

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

Something like:

distance = fields.Float(string='Distance', compute='_compute_distance')
  @api.depends('address')
def _compute_distance(self):
     ...code
     self.distance = X
Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
6
thg 6 17
23223
3
thg 9 23
2297
2
thg 3 15
5767
1
thg 2 24
1427
1
thg 3 15
4263