Состояния модели для рабочих процессов в Odoo

Я пытаюсь реализовать рабочие процессы публикации Odoo для моей пользовательской модели product_images.product_image.

Мои модели выглядят так:

# product_images/models/models.py
# -*- coding: utf-8 -*-
from odoo import models, fields, api, tools

class PublishingStatus(models.Model):
    _name = 'product_images.publishing_status'
    _description = 'Publishing status'

    name = fields.Char(string="Name")
    slug = fields.Char(string="Slug")


class ProductImage(models.Model):
    _name = 'product_images.product_image'
    _description = 'Product image'

    name = fields.Char(string="Alternative text")
    product_id = fields.Many2one('product.product', string='Product', ondelete='set null', index=True)
    original_image = fields.Binary(string='Original image')

    @api.model
    def _get_default_state(self):
        return self.env['product_images.publishing_status'].search([['slug', '=', 'draft']])

    @api.model
    def _get_all_states(self, groups, domain, order):
        state_ids = self.env['product_images.publishing_status'].search([])
        return state_ids

    state_id = fields.Many2one(
        'product_images.publishing_status',
        string='Publishing status',
        default=_get_default_state,
        group_expand='_get_all_states',
    )

    @api.multi
    def action_set_to_draft(self):
        self.state_id = self.env['product_images.publishing_status'].search([['slug', '=', 'draft']])

    @api.multi
    def action_request_for_approval(self):
        self.state_id = self.env['product_images.publishing_status'].search([['slug', '=', 'pending']])

    @api.multi
    def action_approve(self):
        self.state_id = self.env['product_images.publishing_status'].search([['slug', '=', 'approved']])

    @api.multi
    def action_reject(self):
        self.state_id = self.env['product_images.publishing_status'].search([['slug', '=', 'rejected']])

Затем у меня есть записи данных для статусов публикации:

<!-- product_images/data/data.xml -->
<odoo>
    <data>
        <!-- explicit list view definition -->
        <record model="product_images.publishing_status" id="product_images.publishing_status_draft">
            <field name="name">Draft</field>
            <field name="slug">draft</field>
        </record>
        <record model="product_images.publishing_status" id="product_images.publishing_status_pending">
            <field name="name">Pending</field>
            <field name="slug">pending</field>
        </record>
        <record model="product_images.publishing_status" id="product_images.publishing_status_approved">
            <field name="name">Approved</field>
            <field name="slug">approved</field>
        </record>
        <record model="product_images.publishing_status" id="product_images.publishing_status_rejected">
            <field name="name">Rejected</field>
            <field name="slug">rejected</field>
        </record>
    </data>
</odoo>

У меня также есть несколько записей для создания рабочего процесса, который позволяет переключаться между статусами публикации:

<odoo>
    <data>
        <record model="workflow" id="product_images.wkf_image_publishing">
            <field name="name">Product Image Publishing Workflow</field>
            <field name="osv">product_images.product_image</field>
            <field name="on_create">True</field>
        </record>

        <record model="workflow.activity" id="product_images.wkf_activity_draft">
            <field name="name">Draft</field>
            <field name="wkf_id" ref="product_images.wkf_image_publishing" />
            <field name="flow_start" eval="True" />
            <field name="kind">function</field>
            <field name="action">action_set_to_draft()</field>
        </record>
        <record model="workflow.activity" id="product_images.wkf_activity_pending">
            <field name="name">Pending</field>
            <field name="wkf_id" ref="product_images.wkf_image_publishing" />
            <field name="kind">function</field>
            <field name="action">action_request_for_approval()</field>
        </record>
        <record model="workflow.activity" id="product_images.wkf_activity_approved">
            <field name="name">Approved</field>
            <field name="wkf_id" ref="product_images.wkf_image_publishing" />
            <field name="flow_stop" eval="True" />
            <field name="kind">function</field>
            <field name="action">action_approve()</field>
        </record>
        <record model="workflow.activity" id="product_images.wkf_activity_rejected">
            <field name="name">Rejected</field>
            <field name="wkf_id" ref="product_images.wkf_image_publishing" />
            <field name="flow_stop" eval="True" />
            <field name="kind">function</field>
            <field name="action">action_reject()</field>
        </record>

        <record model="workflow.transition" id="product_images.wkf_transition_draft_to_pending">
            <field name="act_from" ref="product_images.wkf_activity_draft" />
            <field name="act_to" ref="product_images.wkf_activity_pending" />
            <field name="condition">name != "" and original_image != ""</field>
            <field name="signal">pending</field>
        </record>
        <record model="workflow.transition" id="product_images.wkf_transition_pending_to_draft">
            <field name="act_from" ref="product_images.wkf_activity_pending" />
            <field name="act_to" ref="product_images.wkf_activity_draft" />
            <field name="signal">draft</field>
        </record>
        <record model="workflow.transition" id="product_images.wkf_transition_pending_to_approved">
            <field name="act_from" ref="product_images.wkf_activity_pending" />
            <field name="act_to" ref="product_images.wkf_activity_approved" />
            <field name="signal">approve</field>
        </record>
        <record model="workflow.transition" id="product_images.wkf_transition_pending_to_rejected">
            <field name="act_from" ref="product_images.wkf_activity_pending" />
            <field name="act_to" ref="product_images.wkf_activity_rejected" />
            <field name="signal">reject</field>
        </record>
    </data>
</odoo>

А теперь самое интересное! Мне нужна форма с кнопками для переключения между состояниями рабочего процесса и строка состояния, показывающая текущий активный статус. Вот что я пробовал:

    <record model="ir.ui.view" id="product_images.form">
        <field name="name">Product Image</field>
        <field name="model">product_images.product_image</field>
        <field name="arch" type="xml">
            <form>
                <header>
                    <!--
                    <button name="draft"
                            type="workflow"
                            string="Set to draft"
                            attrs="{'invisible': [('state_id.slug','not in',['pending'])]}"
                    />
                    <button name="pending"
                            type="workflow"
                            string="Request for approval"
                            attrs="{'invisible': [('state_id.slug','not in',['draft'])]}"
                    />
                    <button name="approve" 
                            type="workflow"
                            string="Approve"
                            attrs="{'invisible': [('state_id.slug','not in',['pending'])]}"
                            class="oe_highlight"
                    />
                    <button name="reject" 
                            type="workflow"
                            string="Reject"
                            attrs="{'invisible': [('state_id.slug','not in',['pending'])]}"
                            class="oe_highlight"
                    />
                    -->
                    <field name="state_id" widget="statusbar" />
                </header>

                <sheet>
                    <group>
                        <field name="product_id" />
                        <field name="name" string="Alternative text" />
                        <field name="original_image" widget="image" class="oe_avatar" />
                        <field name="state_id" />
                    </group>
                </sheet>
            </form>
        </field>
    </record>

Проблемы у меня появились:

  1. Строка состояния отображается, но текущий статус публикации не активирован.
  2. Если я раскомментирую кнопки, они выдадут ошибку о недопустимом домене:

Неперехваченная ошибка: неизвестное поле state_id.slug в домене [["state_id.slug", "not in", ["pending"]]]

Что мне не хватает?


person Aidas Bendoraitis    schedule 24.11.2016    source источник


Ответы (1)


В атрибуте domain мы не можем использовать родительское поле в левой части. В вашем случае нам нужно добавить связанное поле.

Например:

class ProductImage(models.Model):
    _name = 'product_images.product_image'

    slug = fields.Char(related='state_id.slug', string='Slug', store=True)

Поместите поле slug после state_id в файл представления

<field name="slug" invisible="1"/>

Теперь раскомментируйте <button> коды.

После этого перезапустите сервер Odoo и обновите свой собственный модуль.

person Bhavesh Odedra    schedule 25.11.2016
comment
Спасибо. Это сработало. Мне просто пришлось изменить кнопки следующим образом: ‹имя кнопки = тип утверждения = строка рабочего процесса = Утвердить attrs = {'невидимый': [('slug', 'not in', ['pending'])]} class = oe_highlight / › - person Aidas Bendoraitis; 29.11.2016
comment
Да исправить. Не нужно указывать state_id.slug в button attrs. - person Bhavesh Odedra; 30.11.2016