Is it possible to make a one2many relation without specifying the target model's “foreign key field”?

给你一囗甜甜゛ 提交于 2020-01-24 00:54:06

问题


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.

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

Here's an example:

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

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?


回答1:


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



回答2:


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




回答3:


class citys(models.Model):
    _inherit='purchase.order'
    city_partner=fields.One2many('city.line','city_id',string='City')
#relation between type of base class
class city(models.Model):
    _name='city.line'
    city_id=fields.Many2one('purchase.order')


来源:https://stackoverflow.com/questions/29962101/is-it-possible-to-make-a-one2many-relation-without-specifying-the-target-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!