my problem is that when i saved the fields in model's from B , i did't saw the result in model's view A execept the name of empoyee and department becuse declared in the same model, some freinds suggeste me to use onchnage function but how !!
class FeuilleTemps(models.Model): # A
_name = 'tbrh.feuilletemps'
_rec_name = 'name_emp'
name_emp = fields.Many2one('hr.employee', string="Employé")
name_dep = fields.Many2one('hr.department', string="Département")
abscence_ids = fields.One2many('tbrh.abscences', 'feuille_id', string="ma liste ")
relation_id = fields.Many2one('tbrh.abscences')
date2 = fields.Date(related='relation_id.date', store=True, use_parent_address=False)
statut = fields.Selection(related='relation_id.statut', store=True)
class Abscences(models.Model): # B
_name = 'tbrh.abscences'
statut = fields.Selection([('abscent', 'Abscent'), ('present', 'Présent')], string="Statut")
date = fields.Date()
feuille_id = fields.Many2one('tbrh.feuilletemps',
ondelete='cascade', string="feuille ", required=True)
Related
I would like to create a field that has several categories of professions (parent elements) and at the end the profession corresponding to that category appears, as in the product category field of the product model.
How can I do this?
You can define a computed field that shows the parent categories' names and set it as the _rec_name to let Odoo use it as a display name in the Many2one fields.
Example:
class ProfessionCategory(models.Model):
_name = "profession.category"
_description = "Profession Category"
_rec_name = 'complete_name'
name = fields.Char('Name', index=True, required=True)
complete_name = fields.Char(
'Complete Name', compute='_compute_complete_name', recursive=True,
store=True)
parent_id = fields.Many2one('profession.category', 'Parent Category', index=True, ondelete='cascade')
#api.depends('name', 'parent_id.complete_name')
def _compute_complete_name(self):
for category in self:
if category.parent_id:
category.complete_name = '%s / %s' % (category.parent_id.complete_name, category.name)
else:
category.complete_name = category.name
I have two models, TextMessage and Device, that are related many TextMessages to one Device.
from odoo import models, fields, api
class Device(models.Model):
_name = 'device'
_description = 'A model for storing all devices'
name = fields.Char()
iden = fields.Char()
model_name = fields.Char()
manufacturer = fields.Char()
push_token = fields.Char()
app_version = fields.Integer()
icon = fields.Char()
has_sms = fields.Char()
text_message_ids = fields.One2many("text_message", "device_id", string="Text Messages")
from odoo import models, fields, api
class TextMessage(models.Model):
_name = 'text_message'
_description = 'Text Messages'
name = fields.Char()
message_text = fields.Text()
pb_response = fields.Text()
target_number = fields.Char()
device_id = fields.Many2one('device', 'Device', required=True)
#api.model
#api.depends("device_id")
def create(self, values):
print("values['device_id']",values["device_id"])
print("self.device_id",self.device_id.iden)
for rec in self.device_id:
print("Device ID",rec.iden)
values['pb_response'] = rec.device_id.iden
return super().create(values)
In the create method of TextMessage, I want to retrieve the value of the iden attribute of the Device model.
The print statements in TextMessage.create print:
values['device_id'] 1
self.device_id False
The print statement in the loop prints nothing.
You can't access self before creating the record so it will be false.
You can write the create method in two ways:
Create the record first and then get the iden value:
#api.model
def create(self, values):
res = super().create(values)
res.pb_response = res.device_id.iden
return res
Or you can get the device_id record from values as below:
#api.model
def create(self, values):
if 'device_id' in values and values.get('device_id',False):
device = self.env['device'].browse(values.get('device_id'))
if device:
values['pb_response'] = device.iden
return super().create(values)
If the pb_response field is the same of the iden field then you can create it as related field to device_id.iden and you will get the iden value automatically once the device-id assigned as below:
pb_response = fields.Char(related="device_id.iden")
I created a Flask app with a database, with following classes:
db = SQLAlchemy(app)
class Category(db.Model):
__tablename__ = 'Category'
children = relationship("Child")
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.Text())
icon = db.Column(db.Text())
subcategories = db.relationship('Subcategory', backref="category")
def __init__(self, name, subcategories, icon):
self.name = name
self.color = icon
self.subcategories = subcategories
class Subcategory(db.Model):
__tablename__ = 'Subcategory'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.Text())
color = db.Column(db.Text())
reward_points = db.Column(db.Integer())
category = db.Column(db.Text())
tasks = db.relationship('Task', backref="subcategory")
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
def __init__(self, name, color, reward_points, category, tasks, category_id):
self.name = name
self.color = color
self.reward_points = reward_points
self.category = category
self.tasks = tasks
self.category_id = category_id
class Task(db.Model):
__tablename__ = 'Task'
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
task = db.Column(db.Text())
start = db.Column(db.DateTime())
end = db.Column(db.DateTime())
duration = db.Column(db.Integer)
scheduled = db.Column(db.DateTime())
created = db.Column(db.DateTime())
status = db.Column(db.Text())
category = db.Column(db.Text())
subcategory = db.Column(db.Text())
tags = db.Column(db.Text())
subcategory_id = db.Column(db.Integer, db.ForeignKey('subcategory.id'))
def __init__(self, task, start, end, duration, category, subcategory, tags, created, status, scheduled, subcategory_id):
self.task = task
self.start = start
self.end = end
self.duration = duration
self.category = category
self.subcategory = subcategory
self.tags = tags
self.created = created
self.status = status
self.scheduled = scheduled
self.subcategory_id = subcategory_id
My goal is to create one to many relationships between the classes. I am trying to run the db.create_all() command, but am getting following error:
sqlalchemy.exc.NoReferencedTableError: Foreign key associated with column 'Subcategory.category_id' could not find table 'category' with which to generate a foreign key to target column 'id'
What am I doing wrong? Other questions on Stackoverflow with similar issues did not resolve my error.
Changing
category_id = db.Column(db.Integer, db.ForeignKey('category.id'))
to
category_id = db.Column(db.Integer, db.ForeignKey('Category.id'))
solved the issue.
Changing "category.id" to "category.c.id" solved the issue as well. If anyone knows why, pls let me know ;-)
I'm trying to convert an SQL query into django format but as I'm quite new to django I'm having some trouble.
My query:
select make_name, count(*) as count from main_app_make as make
join main_app_model as model on make.id = model.make_id
join main_app_vehicle as vehicle on model.id = vehicle.model_id
group by make.make_name
The result:
Audi 1
Mercedes-Benz 2
My models:
class Make(models.Model):
make_name = models.CharField(max_length=50)
make_logo = models.CharField(max_length=400)
def __str__(self):
return self.make_name
class Model(models.Model):
model_name = models.CharField(max_length=50)
make = models.ForeignKey(Make, on_delete=models.CASCADE)
def __str__(self):
return self.model_name
class Vehicle(models.Model):
type = models.ForeignKey(VehicleType, on_delete=models.CASCADE)
model = models.ForeignKey(Model, on_delete=models.CASCADE)
body_type = models.ForeignKey(Body, on_delete=models.CASCADE)
...
This is what I tried:
options = Make.objects.all().values('make_name').annotate(total=Count('make_name'))
I think you need to include the children models in the Count :
options = Make.objects.values('make_name').annotate(total=Count('model_set__vehicle_set'))
Reference : https://docs.djangoproject.com/en/stable/topics/db/aggregation/#following-relationships-backwards
class base(models.Model):
_name = 'base'
name = fields.Char("Name")
c_id = fields.Many2one('base.ch')
class base_ch(models.Model):
_name = 'base.ch'
name = fields.Char("Name")
q_ids = fields.One2many("base.q","c_id")
class base_q(models.Model):
_name = "base.q"
name = fields.Char("Name")
c_id = fields.Many2one('base.ch',"Basec")
class base_h(models.Model):
_name = "base.h"
name = fields.Char("Name")
select = fields.Selection([('a', 'A'), ('b', 'B')], "select")
desc = fields.Char("Desc")
I have these classes and I want to add in the base class a field of the base_h class in tree view format.
I need to do an onchange function in the base class that when choosing c_id modify the name field of the added field of the base_h class with the records of c_id.q_ids
I tried:
#api.onchange('ch_id')
def onchange_ch(self):
if self.ch_id.q_ids:
self.one2manyfield.name = [(6, 0, self.ch_id.q_ids)]
#also with-> self.one2manyfield = [(6, 0, self.ch_id.q_ids)]
But it does not work
(6, 0, [IDs]) will take list of ids.
Try with following code.
#api.onchange('ch_id')
def onchange_ch(self):
if self.ch_id and self.ch_id.q_ids:
one2manyfield = [(6, 0, self.cht_id.q_ids.ids)]
This is the function that works
#api.onchange('ch_id')
def onch_ch(self):
valors = []
for r in self.ch_id.q_ids:
register = {'name': r.name}
valors.append(register)
self.one2manyfield = valors