簡體   English   中英

如果模型的數據庫與 Odoo 中其他模型的數據庫存在多對多關系,如何更新模型的數據庫?

[英]How to update the Model's database if it has Many2many relation with other Model's database in Odoo?

我有 2 個模型“書”和“作者”。 我在他們之間有 Many2many 關系。如果從作者數據庫中刪除了一個作者,我應該刪除所有作者寫的書。我嘗試了很多方法,但我是 Odoo 的新手。 所以我不能。 解決方案是什么? 謝謝。

書.py

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

作者.py

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)

我不明白的一件事如果這本書是由兩位作者寫的怎么辦! 如果不是這種情況,那么關系應該是 one2many。

你說這兩個模型之間有many2many關系:

  1. 您的 many2many 字段在書籍模型author_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"""
        books = self.env['about.book'].search([('author_ids', 'in', self.ids)]
        if books:
            books.unlink()
        return super(Author, self).unlink()
  1. 第二種學習情況,如果在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()
        
    

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM