本文介绍了是否可以在不指定目标模型的“外键字段"的情况下建立一对多关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一个与one2many有关系的superclass,并说dummy.one.这样,每个继承superclasssubclass都会与dummy.one具有one2many关系.问题是声明one2many关系迫使我指定将dummy.one链接到superclass的外键.因此,我需要为我创建的每个subclassdummy.one中创建many2one关系(外键).

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.

唯一可行的技巧是我创建一个many2many关系而不是one2many.

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

这是一个例子:

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

Many2Many:

Many2Many:

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

是否有更好的方法可以实现与many2many相同的效果,而不必为每个subclassdummy.one中声明many2one字段?

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?

推荐答案

您可能更喜欢使用Odoo的ORM继承,该继承是委派的继承,而不是使用Python继承.请参见以下示例:

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:

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()

这篇关于是否可以在不指定目标模型的“外键字段"的情况下建立一对多关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-16 08:44