Skip to Content
Odoo Menú
  • Registra entrada
  • Prova-ho gratis
  • Aplicacions
    Finances
    • Comptabilitat
    • Facturació
    • Despeses
    • Full de càlcul (IA)
    • Documents
    • Signatura
    Vendes
    • CRM
    • Vendes
    • Punt de venda per a botigues
    • Punt de venda per a restaurants
    • Subscripcions
    • Lloguer
    Imatges de llocs web
    • Creació de llocs web
    • Comerç electrònic
    • Blog
    • Fòrum
    • Xat en directe
    • Aprenentatge en línia
    Cadena de subministrament
    • Inventari
    • Fabricació
    • PLM
    • Compres
    • Manteniment
    • Qualitat
    Recursos humans
    • Empleats
    • Reclutament
    • Absències
    • Avaluacions
    • Recomanacions
    • Flota
    Màrqueting
    • Màrqueting Social
    • Màrqueting per correu electrònic
    • Màrqueting per SMS
    • Esdeveniments
    • Automatització del màrqueting
    • Enquestes
    Serveis
    • Projectes
    • Fulls d'hores
    • Servei de camp
    • Suport
    • Planificació
    • Cites
    Productivitat
    • Converses
    • Validacions
    • IoT
    • VoIP
    • Coneixements
    • WhatsApp
    Aplicacions de tercers Odoo Studio Plataforma d'Odoo al núvol
  • Sectors
    Comerç al detall
    • Llibreria
    • Botiga de roba
    • Botiga de mobles
    • Botiga d'ultramarins
    • Ferreteria
    • Botiga de joguines
    Food & Hospitality
    • Bar i pub
    • Restaurant
    • Menjar ràpid
    • Guest House
    • Distribuïdor de begudes
    • Hotel
    Immobiliari
    • Agència immobiliària
    • Estudi d'arquitectura
    • Construcció
    • Gestió immobiliària
    • Jardineria
    • Associació de propietaris de béns immobles
    Consultoria
    • Empresa comptable
    • Partner d'Odoo
    • Agència de màrqueting
    • Bufet d'advocats
    • Captació de talent
    • Auditoria i certificació
    Fabricació
    • Textile
    • Metal
    • Mobles
    • Menjar
    • Brewery
    • Regals corporatius
    Salut i fitness
    • Club d'esport
    • Òptica
    • Centre de fitness
    • Especialistes en benestar
    • Farmàcia
    • Perruqueria
    Trades
    • Servei de manteniment
    • Hardware i suport informàtic
    • Sistemes d'energia solar
    • Shoe Maker
    • Serveis de neteja
    • Instal·lacions HVAC
    Altres
    • Nonprofit Organization
    • Agència del medi ambient
    • Lloguer de panells publicitaris
    • Fotografia
    • Lloguer de bicicletes
    • Distribuïdors de programari
    Browse all Industries
  • Comunitat
    Aprèn
    • Tutorials
    • Documentació
    • Certificacions
    • Formació
    • Blog
    • Pòdcast
    Potenciar l'educació
    • Programa educatiu
    • Scale-Up! El joc empresarial
    • Visita Odoo
    Obtindre el programari
    • Descarregar
    • Comparar edicions
    • Novetats de les versions
    Col·laborar
    • GitHub
    • Fòrum
    • Esdeveniments
    • Traduccions
    • Converteix-te en partner
    • Services for Partners
    • Registra la teva empresa comptable
    Obtindre els serveis
    • Troba un partner
    • Troba un comptable
    • Contacta amb un expert
    • Serveis d'implementació
    • Referències del client
    • Suport
    • Actualitzacions
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Programar una demo
  • Preus
  • Ajuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Comptabilitat
  • Inventari
  • PoS
  • Projectes
  • MRP
All apps
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
You need to be registered to interact with the community.
All Posts People Badges
Etiquetes (View all)
odoo accounting v14 pos v15
About this forum
Ajuda

How to create and save my own Sale.Order model?

Subscriure's

Get notified when there's activity on this post

This question has been flagged
sale.order.linesale.order12.
8920 Vistes
Avatar
thanhps

Hi, 

I would like to copy and create my own new sale.order model and save data into a separate table in database. Therefore, I am using '_inherit' with '_name' in new model.

However, sale.order also include sale.order.line then I create my own new 'sale.order.line' as above.

When I tried to click Save button, I got the error below: 

-> raise TypeError("Mixing apples and oranges: %s - %s" % (self, other))

Here is my source code

class MyOrder(models.Model):
_name = "my.order"
_inherit = 'sale.order'
_description = "Sale Order"

order_line = fields.One2many('my.order.line', 'order_id', string='Order Lines',
states={'cancel': [('readonly', True)], 'done': [('readonly', True)]}, copy=True,
auto_join=True)
state = fields.Selection([
('draft', 'Draft'),
('sale', 'Sales Order'),
('done', 'Locked'),
('cancel', 'Cancelled'),
], string='Status', readonly=True, copy=False, index=True, track_visibility='onchange', track_sequence=3,
default='draft')

@api.model_cr
def init(self):
self._cr.execute("""
ALTER TABLE public.my_order ALTER COLUMN warehouse_id DROP NOT NULL;
ALTER TABLE public.my_order ALTER COLUMN picking_policy DROP NOT NULL;
ALTER TABLE public.my_order ALTER COLUMN partner_invoice_id DROP NOT NULL;
ALTER TABLE public.my_order ALTER COLUMN partner_shipping_id DROP NOT NULL;
ALTER TABLE public.my_order ALTER COLUMN team_group DROP NOT NULL;
""")

@api.model
def create(self, vals):
if vals.get('name', _('New')) == _('New'):
if 'company_id' in vals:
vals['name'] = self.env['ir.sequence'].with_context(force_company=vals['company_id']).next_by_code(
'my.order') or _('New')
else:
vals['name'] = self.env['ir.sequence'].next_by_code('my.order') or _('New')

# Makes sure 'pricelist_id' are defined
if any(f not in vals for f in ['pricelist_id']):
partner = self.env['res.partner'].browse(vals.get('partner_id'))
vals['pricelist_id'] = vals.setdefault('pricelist_id',
partner.property_product_pricelist and partner.property_product_pricelist.id)
# Change state of order to 'sale'
vals['state'] = 'sale'
vals['date_order'] = fields.Date.today()
return super(MyOrder, self).create(vals)

​
class MyOrderLine(models.Model):
_name = 'my.order.line'
_inherit = 'sale.order.line'
_description = 'Sales Order Line'

order_id = fields.Many2one('my.order', string='Order Reference', required=True, ondelete='cascade',
index=True,
copy=False)

state = fields.Selection([
('draft', 'Draft'),
('sale', 'Sales Order'),
('done', 'Done'),
('cancel', 'Cancelled'),
], related='order_id.state', string='Order Status', readonly=True, copy=False, store=True, default='draft')

@api.model_cr
def init(self):
self._cr.execute("""
ALTER TABLE public.my_order_line ALTER COLUMN customer_lead DROP NOT NULL;
""")

# Override for non-checking inventory
@api.onchange('product_uom_qty')
def _onchange_product_uom_qty(self):
return {}

# Override for non-checking inventory
@api.onchange('product_uom_qty', 'product_uom', 'route_id')
def _onchange_product_id_check_availability(self):
return {}


Thank you for your help!

0
Avatar
Descartar
Niyas Raphy (Walnut Software Solutions)

Better you can use inherits the model sale.order such a way that while creating record it will get added in both models. By default in odoo, you will get example with the product.product model and product.template model.

In the product.product model there is a many2one relation to product.template model, and also product.product model is created using the _inherits

thanhps
Autor

But it inherits only fields not methods, right?

I still want to use some compute methods in sale.order to compute price or total.

Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Registrar-se
Related Posts Respostes Vistes Activitat
Merge Same Item in Sale Order Line Solved
sale.order.line sale.order
Avatar
Avatar
Avatar
2
de gen. 24
6260
Combine inline editing with more detailed form view
sale.order.line sale.order
Avatar
0
de juny 23
2750
ValueError: <class 'ValueError'>: "Expected singleton: sale.order.line(<NewId ref='virtual_117'>, <NewId ref='virtual_131'>)"
sale.order.line sale.order
Avatar
Avatar
1
de des. 22
4186
How to update a custom field as "Margin" default from sale.order does, when some product of sale.order.line is updated/deleted.
sale.order.line sale.order
Avatar
0
d’abr. 22
3218
How to get partner_id from sale.order.line? Solved
sale.order.line 12.
Avatar
Avatar
1
de juny 19
9505
Community
  • Tutorials
  • Documentació
  • Fòrum
Codi obert
  • Descarregar
  • GitHub
  • Runbot
  • Traduccions
Serveis
  • Allotjament a Odoo.sh
  • Suport
  • Actualització
  • Desenvolupaments personalitzats
  • Educació
  • Troba un comptable
  • Troba un partner
  • Converteix-te en partner
Sobre nosaltres
  • La nostra empresa
  • Actius de marca
  • Contacta amb nosaltres
  • Llocs de treball
  • Esdeveniments
  • Pòdcast
  • Blog
  • Clients
  • Informació legal • Privacitat
  • Seguretat
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo és un conjunt d'aplicacions empresarials de codi obert que cobreix totes les necessitats de la teva empresa: CRM, comerç electrònic, comptabilitat, inventari, punt de venda, gestió de projectes, etc.

La proposta única de valor d'Odoo és ser molt fàcil d'utilitzar i estar totalment integrat, ambdues alhora.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now