如果它与Odoo中的其他Model数据库有Many2many关系,如何更新Model的数据库?

问题描述 投票:1回答:1

我有2个模型“书”和“作者”。我之间有很多关系。如果其中一个作者从作者数据库中删除,我应该删除所有从这位作者写的书。我尝试了很多方法,但我是Odoo的新手。所以我不能。解决方案是什么?谢谢。

book.朋友

# -*- coding: utf-8 -*-
from odoo import models, fields,api

class Book(models.Model):
    _name = 'about.book'
    _description = 'Book Information'
    _order = 'publication_date desc, name'
    isbn = fields.Char('ISBN',required=True)
    name = fields.Char('Title', required=True)
    publication_date = fields.Date('Publication Date')
    author_ids = fields.Many2many('about.author', select=True, required=True,string='Authors')
    _sql_constraints = [('isbn_uniq', 'unique (isbn)','ISBN already exists!')]



    @api.constrains('publication_date')
    def _check_publication_date(self):
        for r in self:
            if (r.publication_date > fields.Date.today()) and (r.publication_date == False):
                raise models.ValidationError('Publication date must be in the past !')



    @api.constrains('author_ids')    
    def has_author(self):
        for r in self:
            if r.author_ids == False:
                raise models.ValidationError('Book must have at least 1 author!')

    @api.one
    def unlink(self):
        rule = self.env['about.book']
        if rule.search([('author_ids', '=', False)]):
           rule.unlink()

author.朋友

from odoo import models, fields,api

class Author(models.Model):
    _name='about.author'
    _inherits = {'res.partner' : 'partner_id'}
    partner_id = fields.Many2one('res.partner', string="Author")
    is_book_author= fields.Boolean('Is Book Author',required=True,default=False)
python openerp odoo-10
1个回答
0
投票

有一点我不明白如果这些书是由两位作者写的!如果不是这种情况,那么关系应该是one2many。

你说你在这两个模型之间有很多关系:

1-你在书籍模型author_ids中声明了很多2个字段。

# override unlink of Author not book
class Author(models.Model):
    _name='about.author'
    ......
    ......

    @api.multi
    def unlink(self):
        """when delete author we should delete his books"""
        books = self.env['about.book'].search([('author_ids', 'in', self.ids)]
        if books:
            books.unlink()
        return super(Author, self).unlink()

学习的第二个案例,如果在author模型中声明了many2many字段,我们假设:book_ids

# override unlink of Author not book
class Author(models.Model):
    _name='about.author'

    @api.multi
    def unlink(self):
        """when delete author we should delete his books"""
        # use mapped to return all list of books of all record that
        # will be removed to call unlink one time avoid loop
        books = self.mapped('books_ids')
        if books:
            books.unlink()
        return super(AuthorClass, self).unlink()
© www.soinside.com 2019 - 2024. All rights reserved.