Hi I created the following model:
class PrescriptionsPrescriptions(models.Model):
_name = 'prescriptions.prescriptions'
name = fields.Many2one('res.users','Name', default=lambda self: self.env.user, readonly=True)
Date_entered = fields.Date(string='Date', default=fields.Date.today())
paper_prescriptions = fields.Selection([('yes', 'Yes'), ('no', 'No')], string='Paper Prescriptions?')
However I cannot get the _sql_constraints to work:
_sql_constraints = [('log_unique','unique(name,Date_entered)','You have already logged data for that date.')]
I'm trying to get it so that each person can log only one prescription per Date_entered. Would greatly appreciate any help. :)
Odoo will not be able to add the constraint because of a psycopg2.ProgrammingError
column "date_entered" named in key does not exist
You just need to rename it to date_entered and update the module.
First you can’t have capital letters as starting of your variable.
Second the only reason constraints don’t work after updating is when there is already data violating the constraints
Related
In my model, client_id must be one per product. So I want to make a constraint for this situation.
class ClientSystemCode(models.Model):
_name = 'client.system.code'
_description = 'Client System Code'
client_id = fields.Many2one('res.partner', 'Client')
product_id = fields.Many2one('product.template', 'Product')
client_sys_code = fields.Char('Client system code')
in product.template model my constraints look like this.
#api.constrains('client_system_code_ids')
def _client_system_code_constraint(self):
duplicates = []
for line in self.client_system_code_ids:
if line.client_id.id not in duplicates:
duplicates.append(line.client_id.id)
else:
raise ValidationError(_("Product can't have more than one client code with same client"))
it is ok as it triggered from product form view and there always be not that much lines. But constraint in client.system.code should be better performance wise because there can be thousands of lines. So is there any kind of better solutions?
You will get it done easily using an sql constraint like:
class ClientSystemCode(models.Model):
_name = 'client.system.code'
_sql_constraints = [
('client_product_unique', 'unique (client_id, product_id)', 'Product can't have more than one client code with same client'),
]
How in custom module odoo 9 before insert new record in database, check is record exists?
For example:
If in table project.task we have name "PARIS" and date_deadline "2017-01-01" in code below I need warning before execute...
vals = {'name': 'PARIS','date_deadline': '2017-01-01']}
create_new_task = http.request.env['project.task'].create(vals)
Or maybe try get count from project.task where name='PARIS' and date_deadline='2017-01-01' before click on button save!
Any simple solution?
#api.one
#api.constrains('date','time') #Time is Many2one
def _check_existing(self):
count = self.env['test.module'].search_count([('date','=',self.date),('time','=',self.time.id)])
print(self.date) #2017-01-01
print(self.time.id) #1
if(count >= 1):
raise ValidationError(_('DUPLICATE!'))
After try insert new record in database where is date = 2017-02-02 and time = 1 get this message:
duplicate key value violates unique constraint "test_module_time_uniq"
DETAIL: Key (time)=(1) already exists.
Time exist but date is different! I need constrains for 2 value! In databse I have only one row where is date = 2017-01-01 and time = 1
if you want to prevent duplicated record use sql_constrains
class ModelClass(models.Model):
_name = 'model.name'
# your fields ...
# add unique constraints
sql_constraints = [
('name_task_uniq', 'UNIQUE (name,date_deadline)', 'all ready got a task with this name and this date')
]
# or use api.constrains if you constrains cannot be don in postgreSQL
#api.constrains('name', 'date_deadline')
def _check_existing(self):
# add you logic to check you constrain
duplicate key value violates unique constraint "test_module_time_uniq"
DETAIL: Key (time)=(1) already exists.
This error is thrown by the postgres not odoo you all ready have a unique constrain for time only you need to drop it first
NB: Who added the constrains unique is it you when you where testing you code or is someone else? Answer this by comment ^^
ALTER TABLE project_task DROP CONSTRAINT test_module_time_uniq;
You can use something along those lines:
#api.constrains('name', 'date_deadline')
def _check_existing(self):
# Search for entry with these params, and if found:
# raise ValidationError('Item already exists')
This related field working fine in odoo 9, but not in odoo 10. The field customer_id not updated when I create a new record with nomor_hp_id.
nomor_hp_id = fields.Many2one(
string='Nomor hp',
comodel_name='nomor.hp',
ondelete='cascade',
)
customer_id = fields.Many2one(
string='Customer',
related='nomor_hp_id.customer_id',
ondelete='cascade',
store=True,
readonly=True,
)
Try to start new database but the result still not updated.
You have to give comodel name inside Many2one field either it is normal Many2one or related Many2one. Please have a look at below code. You will get your answer.
nomor_hp_id = fields.Many2one(string='Nomor hp', comodel_name='nomor.hp',ondelete='cascade',)
customer_id = fields.Many2one(string='Customer', comodel_name='res.partner', related='nomor_hp_id.customer_id', ondelete='cascade',readonly=True,)
You have to define the reference of which table. Here customer_id is the reference field of the "res_partner" table or "res.partner" model.
This way works fine for me.
customer_id = fields.Many2one(
string='Customer',
related='nomor_hp_id.customer_id',
store=True,
)
I'm making a module for reservations in Odoo 9 and one field of my model is populated based if it's reserved or no. Basically my model is:
class Reservation(models.Model):
....
room_id = fields.Many2one('reservation.room', string="Room")
I've defined an onchange function that return a domain to filter the room_ids that aren't reserved:
#api.onchange('date')
def _set_available_room(self):
.....
return {'domain': {'room_id': [('id', 'in', res)]}}
This works fine and when I set the date, the rooms are filtered ok. My problem is when I save a reservation and enter again to edit it. The room_id field show all values and only when I change the date the room_id is filtered.
I've tried using the domain attribute in the field definition like this, but it doesn't works:
room_id = fields.Many2one('reservation.room', string="Room", domain=lambda self: self._get_available_slots())
How can I filter this field on the load view using my function than search for available rooms?
I have to tables, one is profile and the other is rating.
rating has a field profileid which is primary key to profile.id and a field with rating values. Now I want to find the field with highest rating and display the corresponding profile. Since I'm new to YII framework I'm having troubles with it. Please help me getting out of it. What I'm doing is described below.
$topRage=new CDbCriteria();
$topRage->select="*";
$topRage->alias="t1";
$topRage->order="rateing DESC";
$topRage->join="JOIN `ratings` ON `profile`.`id` = `t1`.`profileId`";
$topRage->limit="1";
Try this :
join='JOIN profile ON profile.id = t1.profileId';
If you are doing this: Ratings::model()->findAll($topRage) , then ratings table is already being queried, so you need to join with profile table.
Edit:
for echo you'll need to do this:
$echo "Rating id: ".$rating->id."| Profile Id: ".$rating->profile->id."| Profile Name: ".$rating->profile->name."| Rating: ".$rating->ratingvalue;
Don't forget to pass $rating from the controller though.
You could also use find($topRage) instead of the findAll($topRage) and remove the limit, but that 's just another way of doing the same thing.
just query without join .
$topRage=new CDbCriteria();
$topRage->select="*";
$topRage->alias="t1";
$topRage->order="rateing DESC";
$topRage->limit="1";
$rating=Ratings::model()->findAll($topRage);
$profile=Profile::model()->findByPk($rating->profileId);