是否可以在不指定目标模型的“外键字段”的情况下建立one2many关系?

时间:2022-10-05 13:14:19

I want to make a superclass that have a one2many relation with says dummy.one. So that every subclass that inherit the superclass will have a one2many relation with dummy.one. The problem is declaring a one2many relation forces me to specify the foreign key which link dummy.one to the superclass. Thus I need to create many2one relation (foreign key) in dummy.one for every subclass that I create.

我想创建一个与dummy.one有一个one2many关系的超类。因此,继承超类的每个子类都将与dummy.one具有one2many关系。问题是声明one2many关系迫使我指定将dummy.one链接到超类的外键。因此,我需要在dummy.one中为我创建的每个子类创建many2one关系(外键)。

The only trick that works is that I create a many2many relation instead of one2many.

唯一有效的技巧是我创建了一个many2many关系而不是one2many。

Here's an example:

这是一个例子:

'dummies'      : fields.one2many('dummy.one','foreign_key','Dummies'),

Many2Many:

Many2Many:

'dummies'      : fields.many2many('dummy.one',string='Dummies'),

Is there any better way to achieve the same effect as many2many without having to declare a many2one field in dummy.one for every subclass?

有没有更好的方法来实现与many2many相同的效果,而不必在dummy.one中为每个子类声明一个many2one字段?

2 个解决方案

#1


2  

Instead of using Python inheritance you may prefer to use the Odoo's ORM inheritance which is inheritance by delegation. Please see the following example:

您可能更喜欢使用Odoo的ORM继承,而不是使用Python继承,而继承是委托继承。请参阅以下示例:

class book(models.Model):
    _name = 'books.book'
    name = fields.Char()
    author = fields.Many2one('books.author')

class author(models.Model):
    _name = 'books.author'
    name = fields.Char()
    books = fields.One2many('books.book', 'author')

class better_author(models.Model):
    _name = 'books.author'
    _inherit = 'books.author'
    curriculum = fields.Text()

#2


1  

Try to create a many2one relation (foreign key) in dummy.one for the superclass not for every subclass.

尝试在dummy.one中为超类创建一个many2one关系(外键),而不是为每个子类创建。

#1


2  

Instead of using Python inheritance you may prefer to use the Odoo's ORM inheritance which is inheritance by delegation. Please see the following example:

您可能更喜欢使用Odoo的ORM继承,而不是使用Python继承,而继承是委托继承。请参阅以下示例:

class book(models.Model):
    _name = 'books.book'
    name = fields.Char()
    author = fields.Many2one('books.author')

class author(models.Model):
    _name = 'books.author'
    name = fields.Char()
    books = fields.One2many('books.book', 'author')

class better_author(models.Model):
    _name = 'books.author'
    _inherit = 'books.author'
    curriculum = fields.Text()

#2


1  

Try to create a many2one relation (foreign key) in dummy.one for the superclass not for every subclass.

尝试在dummy.one中为超类创建一个many2one关系(外键),而不是为每个子类创建。