Ir al contenido
Odoo Menú
  • Iniciar sesión
  • Pruébalo gratis
  • Aplicaciones
    Finanzas
    • Contabilidad
    • Facturación
    • Gastos
    • Hoja de cálculo (BI)
    • Documentos
    • Firma electrónica
    Ventas
    • CRM
    • Ventas
    • PdV para tiendas
    • PdV para restaurantes
    • Suscripciones
    • Alquiler
    Sitios web
    • Creador de sitios web
    • Comercio electrónico
    • Blog
    • Foro
    • Chat en vivo
    • eLearning
    Cadena de suministro
    • Inventario
    • Manufactura
    • PLM
    • Compras
    • Mantenimiento
    • Calidad
    Recursos humanos
    • Empleados
    • Reclutamiento
    • Vacaciones
    • Evaluaciones
    • Referencias
    • Flotilla
    Marketing
    • Redes sociales
    • Marketing por correo
    • Marketing por SMS
    • Eventos
    • Automatización de marketing
    • Encuestas
    Servicios
    • Proyectos
    • Registro de horas
    • Servicio externo
    • Soporte al cliente
    • Planeación
    • Citas
    Productividad
    • Conversaciones
    • Aprobaciones
    • IoT
    • VoIP
    • Artículos
    • WhatsApp
    Aplicaciones externas Studio de Odoo Plataforma de Odoo en la nube
  • Industrias
    Venta minorista
    • Librería
    • Tienda de ropa
    • Mueblería
    • Tienda de abarrotes
    • Ferretería
    • Juguetería
    Alimentos y hospitalidad
    • Bar y pub
    • Restaurante
    • Comida rápida
    • Casa de huéspedes
    • Distribuidora de bebidas
    • Hotel
    Bienes inmuebles
    • Agencia inmobiliaria
    • Estudio de arquitectura
    • Construcción
    • Gestión de bienes inmuebles
    • Jardinería
    • Asociación de propietarios
    Consultoría
    • Firma contable
    • Partner de Odoo
    • Agencia de marketing
    • Bufete de abogados
    • Adquisición de talentos
    • Auditorías y certificaciones
    Manufactura
    • Textil
    • Metal
    • Muebles
    • Comida
    • Cervecería
    • Regalos corporativos
    Salud y ejercicio
    • Club deportivo
    • Óptica
    • Gimnasio
    • Especialistas en bienestar
    • Farmacia
    • Peluquería
    Trades
    • Personal de mantenimiento
    • Hardware y soporte de TI
    • Sistemas de energía solar
    • Zapateros y fabricantes de calzado
    • Servicios de limpieza
    • Servicios de calefacción, ventilación y aire acondicionado
    Otros
    • Organización sin fines de lucro
    • Agencia para la protección del medio ambiente
    • Alquiler de anuncios publicitarios
    • Fotografía
    • Alquiler de bicicletas
    • Distribuidor de software
    Descubre todas las industrias
  • Odoo Community
    Aprende
    • Tutoriales
    • Documentación
    • Certificaciones
    • Capacitación
    • Blog
    • Podcast
    Fortalece la educación
    • Programa educativo
    • Scale Up! El juego empresarial
    • Visita Odoo
    Obtén el software
    • Descargar
    • Compara ediciones
    • Versiones
    Colabora
    • GitHub
    • Foro
    • Eventos
    • Traducciones
    • Conviértete en partner
    • Servicios para partners
    • Registra tu firma contable
    Obtén servicios
    • Encuentra un partner
    • Encuentra un contador
    • Contacta a un consultor
    • Servicios de implementación
    • Referencias de clientes
    • Soporte
    • Actualizaciones
    GitHub YouTube Twitter LinkedIn Instagram Facebook Spotify
    +1 (650) 691-3277
    Solicita una demostración
  • Precios
  • Ayuda

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Contabilidad
  • Inventario
  • PoS
  • Proyectos
  • MRP
All apps
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Debe estar registrado para interactuar con la comunidad.
Todas las publicaciones Personas Insignias
Etiquetas (Ver todo)
odoo accounting v14 pos v15
Acerca de este foro
Ayuda

"Self" Record set is empty

Suscribirse

Reciba una notificación cuando haya actividad en esta publicación

Se marcó esta pregunta
pythonselfv17
4 Respuestas
4058 Vistas
Avatar
IRIG Events

Hello,

I am working on a module where I implement a special, simplified version of a task.

Ithis task model, there are a few standard task types and each of those types comes with a specific set of state stages. 

I have created a table where I can store task types and stage names. I have gotten it so that at the time of creation, the task gets assignedd a specific task type.

Now my issue is that I want to use a callable for the selection field which calls on self to finnd out it's own task type, search for the stages corresponding to this task type and assign them to the selection field.

the theory sounds great, but for some reason, when I call self, it appears to be empty. When I try to debug using the console print, I always get 'irig.task()' (the name of the model) but no records in the recordset. 

can anybody help me figure out what am I calling wrong?

state_test = fields.Selection(selection='get_states')
 
def get_states(self):
  ​sel = [
​ ​('1','One'), ​
​ ​('2','Two') ​
      ]
​print(self) ​
​for r in self:
    ​records = self.env['irig.state'].search([('task_type', 'like', 'gear')])
​## It should llok like this, but the r in self is empty:
.search([('task_type', 'like', r.task_type)])​
​ ​
​ ​for rec in records: ​
        ​sel.append((rec.task_type, rec.name) )
​ ​ ​print(sel) ​
​return sel

In the above snippet, I have tested individual parts and it all works, the only part that since self shows as empty, then 'r in self' is also empty.

Even after the record is created, when I navigate to it, the 'get_states' method is called, but self is still empty.


Any help will be greatly appreciated!

0
Avatar
Descartar
Rithik Sandron

have you overridden the create method to call get_states()?

IRIG Events
Autor

@Rithik Sandron
I just tried it, but it still didn't work.

Avatar
Dương Nguyễn
Mejor respuesta

In your case use compute instead, because self will always empty when you write seletion="your method"

I have searched across odoo 17 code where they have selection="method" and they do not use self just use something like self.env to search for other module

0
Avatar
Descartar
Avatar
IRIG Events
Autor Mejor respuesta

O.k. For some reason I cant comment on anybody elses answers or comments. but after trying and playing with this, I can confirm that on the "selection" field, although it can use a callable function to popullate the options, there is no "self" available. so it is basically impossible to reference itself to choose the options based on some parameter of itself. 


However, I ended up solving my ultimate goal by using a Many2one relationship, with a domain based on a parameter of itself and then using the "statusbar" widget on it. Not the most ideal way, but it works. 


Thank you very much for your help and input.

 

-----------------------------------------------

Previous edit

@Rithik Sandron,

thank you very much for the example, however it doesnt really work.

the logic of getting the record after calling super(etc) works great in the sense that I indeed get a record that I can work with.

The problem now is that If I leave the field

state_test = fields.Selection(selection='get_states')

then, the method gets called before I create the record and every time I look at a record, both moments there is no self.

When I call the method from the create method, although now I do get the correct records and I do have a task to get info out of, it doesnt automatically assign the result to the selection field, and when I try to "force" it by doing:

task.state_test = selection_fields

I get an error saying that it is not the right value, even though it is a list of tuples.

the same behaviour happens when I change the state_test field to this:

state_test = fields.Selection([], string="State Test)

The part I still dont understand is how come when I call pretty much any other method, self does exist all the time, except for only this one method

cheers!

0
Avatar
Descartar
Rithik Sandron

I have updated my answer. Check out if that helps

IRIG Events
Autor

Sadly it still didnt work. However I found out that the 'selection=callable' Method in the selection field doesnt pass 'self'. Dont know if this is a bug or intentional for some reason, but I just tried calling the same 'get_states' method from the seleection field and from a compute on both a selection and a char field and directly from the selection=callable method I never got self, but from the compute I do get self and I can get all the info... However, since the result is a list of tuples, neither the return of a compute nor a direct assignment work.

Thank you very much to both, I will try to go deeper into it tomorrow.

Avatar
Rithik Sandron
Mejor respuesta

If you're overriding the create method, try this:

from odoo import api

state_test = fields.Selection([('1', 'One'),
('2', 'Two'),
('3', 'Three')], string='State Test')

@api.model_create_multi
def create(self, values_list):
​for value in values_list:
​ // here the record has not been created yet, so the self object does not contain the record. self.get_states() will not work
​
​ ​line = super(model_class_name, self).create(vals)
​ // ​here the record has been created. the record object in returned to line
​ ​line.get_states() // this will work
​return line

def get_states(self):
​for record in self:
​ ​record.state_test = '2'

To change selection fields dynamically:

from odoo import models, fields, api


class IrigTask(models.Model):
​_name = "irig.task"
​_description = "irig.task"
​
​@api.model
def ​_get_selection_items(self):
​ sel = [('1', 'One'), ('2', 'Two')]​
​ ​return sel

​state_test = fields.Selection(selection=lambda self: self.env['irig.task']._get_selection_items(), string="State Test")

hope this helps. let me know


0
Avatar
Descartar
Avatar
Cybrosys Techno Solutions Pvt.Ltd
Mejor respuesta

Hi,

Please try to use api.model decorator before the function starts, and maybe in the self you may be getting a False value, If you are getting False in the print, then you can search the value.

example:


@api.model

def get_states(self):

      sel = [

        ('1','One'), ('2','Two') ]

         print(self)

         for r in self.env['model.name'].search([]):

         //your balance code



Hope it helps

-1
Avatar
Descartar
Dương Nguyễn

Wrong purpose of using api.model, learn odoo again please.
When using api.model, we will not take into account value in self which mean we won't use self.'field' at al

¿Le interesa esta conversación? ¡Participe en ella!

Cree una cuenta para poder utilizar funciones exclusivas e interactuar con la comunidad.

Registrarse
Publicaciones relacionadas Respuestas Vistas Actividad
i am using odoo 17. i have a one field 'wage' and it is a salary like number 1254200. i want comma in this number using Indian standard number comma format for example 12,54,200.00 how can i using python ?
python v17
Avatar
Avatar
1
mar 24
1696
Call method using XML RPC
python XML-RPC v17
Avatar
Avatar
1
dic 23
3401
Iteration on self
python self odoo16features
Avatar
Avatar
2
ene 23
3418
Create productvariant and add order
python product.product order.line v17
Avatar
Avatar
1
jul 24
2332
Field used in docstring domain not present in view
python xml odoo16features v17
Avatar
Avatar
1
oct 24
2423
Comunidad
  • Tutoriales
  • Documentación
  • Foro
Código abierto
  • Descargar
  • GitHub
  • Runbot
  • Traducciones
Servicios
  • Alojamiento en Odoo.sh
  • Soporte
  • Actualizaciones del software
  • Desarrollos personalizados
  • Educación
  • Encuentra un contador
  • Encuentra un partner
  • Conviértete en partner
Sobre nosotros
  • Nuestra empresa
  • Activos de marca
  • Contáctanos
  • Empleos
  • Eventos
  • Podcast
  • Blog
  • Clientes
  • Legal • Privacidad
  • Seguridad
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo es un conjunto de aplicaciones de código abierto que cubren todas las necesidades de tu empresa: CRM, comercio electrónico, contabilidad, inventario, punto de venta, gestión de proyectos, etc.

La propuesta única de valor de Odoo es ser muy fácil de usar y estar totalmente integrado.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now