如何在Odoo中存储company_dependent字段?含standard_price存储用于SQL查询需求
Hey there, let's tackle your two Odoo technical needs step by step, using your provided code snippet as a starting point.
1. How Company-Dependent Fields Are Stored in Odoo
When you mark a field with company_dependent=True, Odoo doesn’t store the value directly in the main product.product table. Instead, it automatically creates a relational (join) table to hold company-specific values.
For your standard_price field, this table will typically be named product_product_standard_price_rel, with three core columns:
product_id: Links back to the corresponding product recordcompany_id: Links to the company that owns this specific price valuevalue: Stores the actualstandard_priceamount for the product-company pair
Since you’ve added store=True to your field definition, these values are permanently persisted in this relational table (not calculated dynamically), which is exactly what you need to make them accessible for SQL queries.
2. Using Stored standard_price in SQL Queries
Your code already correctly sets up the standard_price field to be company-dependent and stored. To query this value via SQL, you’ll need to join the main product.product table with the auto-generated relational table.
Here’s a practical example SQL query to fetch products along with their company-specific cost price:
SELECT pp.id AS product_id, pp.name AS product_name, rel.value AS standard_price FROM product_product pp LEFT JOIN product_product_standard_price_rel rel ON pp.id = rel.product_id AND rel.company_id = YOUR_COMPANY_ID; -- Replace with your actual company ID
If you need to retrieve values for all companies, simply remove the AND rel.company_id = ... condition to get all product-company price pairs.
Your Code Snippet (Breakdown)
This is the code you provided, which perfectly implements your requirements:
# -*- coding: utf-8 -*- from odoo import fields, models from odoo.addons import decimal_precision as dp class Product(models.Model): _inherit = "product.product" standard_price = fields.Float( 'Cost', company_dependent=True, digits=dp.get_precision('Product Price'), groups="base.group_user", store=True, help = "Cost used for stock valuation in standard price and as a first price to set..." )
_inherit = "product.product": Extends Odoo's core product model to add your customizationscompany_dependent=True: Enables separate cost prices for each companystore=True: Ensures values are saved to the relational table (critical for SQL access)digits=dp.get_precision('Product Price'): Maintains consistent decimal precision with Odoo's built-in product pricing standards
内容的提问来源于stack exchange,提问作者Ketan Chauhan




