odoo one2many list remove duplicates items - odoo-10

i have developed a module of purchase in odoo 10 community when i make a cammand of products i want to disable duplicate choose of product in widget one2many list as in the image below:
enter image description here
i want to prevent duplicate entry in the products list here is the code of my command module:
class PalBl(models.Model):
_name = 'pal.bl'
name = fields.Char('Reference', required=True)
supplier = fields.Many2one('pal.vendor', required=True)
date = fields.Date('Date', required=True)
totalHt = fields.Float('Total HT', store=True, readonly=True, compute='_get_tot')
totalTtc = fields.Float('Total TTC', store=True, readonly=True, compute='_get_tot')
items_id = fields.One2many('pal.prs.com', 'prod_id')
dateliv = fields.Date('Date de livraison prévue')
nb_pr = fields.Integer('Total de Produit')
state = fields.Selection([(1, 'En attente'), (2, 'Reglée')], 'type', default=1)
_sql_constraints = [('item_code_uniq', 'unique(items_id.name.code)', "le code d'un produit doit etre unique !")]
and this the code of the products:
class PalPrcom(models.Model):
_name = 'pal.prs.com'
name = fields.Many2one('pal.stock', 'Désignation', required=True)
code = fields.Char('Ref produit', store=True, readonly=True, compute='_getref', inverse='_gedef')
quantity = fields.Integer('Quantité', required=True, default=1)
price = fields.Float('Prix achat HT', store=True, readonly=True, compute='_getref')
tva = fields.Integer('TVA')
remise = fields.Integer('Remise')
prod_id = fields.Many2one('pal.bl')
_sql_constraints = [ ('quantity_gt_zero', 'CHECK (quantity>0)', 'La quantité de produit doit etre supérieur à zéro!')
]

You can use two for loops which will iterate over your one2many field and check for duplicates

This will work.
_sql_constraints = [('order_name', 'unique (relation_id,field_name_1,field_name_2)',
'Duplicates are not allowed!')]

Related

I have to filter data in Many2one field

I have to models related to employees, one with contracts
class Contract(models.Model):
_name = 'hr.employee.contract'
_description = "employee contract model"
_rec_name = 'begin_date'
_order = 'begin_date desc'
type = fields.Many2one(string='Contract Type', comodel_name='hr.employee.contract_type')
category = fields.Many2one(string='Contract Category', comodel_name='hr.employee.contract_category')
begin_date = fields.Date(string='Begin Date')
end_date = fields.Date(string='End Date')
work_place = fields.Many2one(comodel_name='hr.employee.vessel', string='Work Place')
enterprise = fields.Char(related='work_place.enterprise.name', string='Enterprise')
sick_leave_reason = fields.Char(string='Sick Leave Reason')
employee = fields.Many2one(comodel_name='hr.employee', string='Employee ID', ondelete='cascade')
crew_member = fields.Many2one(string='Crew Member', comodel_name='hr.employee.crew_member')
internal_contract_id = fields.Integer(string='Internal Contract Id')
contract_code = fields.Integer(string='Contract Code')
And another model in whick I have to store the different work places for a certain contract. Both models are shown as tree list inside the employee card.
class Assignement(models.Model):
_name = 'hr.employee.assignement'
_description = "Employees assignement model"
contract_id = fields.Many2one(comodel_name='hr.employee.contract', string='Contrato')
employee = fields.Many2one(comodel_name='hr.employee', string='Employee ID')
work_place = fields.Many2one(comodel_name='hr.employee.vessel', string='Work Place')
begin_date = fields.Date(string='Begin Date')
end_date = fields.Date(string='End Date')
As it should work, if I edit the employee card which has a certaint number of contracts linked, when I am going to introduce an assignement, when I click on the field contract it should show only contracts of the employee a I am editing.
Help please.
Best regards

Get value from the ListView

can anyone help me with my codes. I want to display the max amount of the fields amount from other .py
and display it on the form view.
Right now with that codes, im getting only the sequence number of the list, not the inputted amount.
**custom_item.py**
class Amount(models.Model):
_name = "custom.item"
_description = "Item List"
_order = 'create_date desc, id desc'
Item_lists_id = fields.Many2one('custom.item', "Items", required=True)
amount = fields.Integer("Amount", store=True)
**custom_account.py**
class Account(models.Model):
_name = "custom.account"
_description = "Account List"
_order = 'create_date desc, id desc'
item_amount_ids = fields.One2many('custom.item', 'account_id', "Item Summary:")
Items_count = fields.Integer("Count Items", compute='_get_grade_count')
amount_max = fields.Integer("High amount:", compute='_get_item_amount')
#api.depends('item_amount_ids')
def _get_item_amount(self):
for rec in self:
rec.amount_max = max(rec.item_amount_ids)

Django TypeError get() argument after ** must be a mapping, not list

I'm creating a serializer for a model with a ManyToManyField (tag_id) that refers to a Tag table.
serializers.py
class CombinationSerializer(serializers.ModelSerializer):
# tag_id = serializers.PrimaryKeyRelatedField(queryset=Tag.objects.all(), source='tag', required=False, many=True)
tag_id = TagWithIdSerializer(many=True, required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Combination
depth = 1
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag_id', 'created', 'score')
def create(self, validated_data):
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
combination = Combination(
user=user,
gameround=validated_data.get("gameround"),
resource=validated_data.get("resource"),
created=datetime.now(),
score=score
)
combination.save()
tag_data = validated_data.pop('tag_id', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag_id'] = tag
combination.tag_id.add(validated_data.get("tag_id"))
return combination
This is the problematic code:
tag_data = validated_data.pop('tag_id', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag_id'] = tag
combination.tag_id.add(validated_data.get("tag_id"))
This is the JSON object I am trying to send in Postman:
{
"gameround_id": 2015685170,
"resource_id": 327888,
"tag_id": [{"id": 2001372884, "name": "combination", "language": "en"}]
}
What am I doing wrong here? Can this be done any other way?
The tag_id maps on a list of dictionaries, not a dictionary. You thus can enumerate over it:
tag_data = validated_data.pop('tag_id', None)
for tag_item in tag_data:
tag = Tag.objects.get_or_create(**tag_item)[0]
validated_data['tag_id'] = tag
since these are lists, it might be better however to make a list of tags in the validated data:
tag_data = validated_data.pop('tag_id', None)
validated_data['tag_id'] = [
Tag.objects.get_or_create(**tag_item)[0]
for tag_item in tag_data
]

Django REST update foreign key by id

Problem:
I want to update a foreign key field and I can not find my mistake why my changes to that fields are not saved. I want to be able to update clan and wingman.
serializer.py
class UpdateProfileInfoSerializer(serializers.Serializer):
id = serializers.CharField(required=True)
wingmanId = serializers.IntegerField(required=False)
clanId = serializers.IntegerField(required=False)
image = serializers.ImageField(required=False)
titleImage = serializers.ImageField(required=False)
description = serializers.CharField(required=False)
class Meta:
model = ProfileInfo
fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']
def update(self, instance, validated_data):
clan_id = validated_data.get('clanId')
wingman_id = validated_data.get('wingmanId')
if clan_id:
if instance.clan:
instance.clan.id = clan_id
if wingman_id:
if instance.wingman:
instance.wingman.id = wingman_id
instance.image = validated_data.get('image', instance.image)
instance.titleImage = validated_data.get('titleImage', instance.titleImage)
instance.description = validated_data.get('description', instance.description)
instance.save()
return instance
Thank you for your help. I think I am doing something fundamentally wrong.
Try this please, I think it is better.
class UpdateProfileInfoSerializer(serializers.Serializer):
id = serializers.CharField(required=True)
wingmanId = serializers.IntegerField(required=False)
clanId = serializers.IntegerField(required=False)
image = serializers.ImageField(required=False)
titleImage = serializers.ImageField(required=False)
description = serializers.CharField(required=False)
class Meta:
model = ProfileInfo
fields = ['id', 'clanId', 'description', 'image', 'titleImage', 'wingmanId']
def update(self, instance, validated_data):
clan_id = validated_data.get('clanId')
wingman_id = validated_data.get('wingmanId')
if clan_id:
if instance.clan:
try:
clan_obj = Clan.objects.get(id=clan_id)
instance.clan = clan_obj
except:
pass
if wingman_id:
if instance.wingman:
try:
wingman_obj = Wingman.objects.get(id=wingman_id)
instance.wingman = wingman_obj
except:
pass
instance.image = validated_data.get('image', instance.image)
instance.titleImage = validated_data.get('titleImage', instance.titleImage)
instance.description = validated_data.get('description', instance.description)
instance.save()
return instance

How to dynamically add domain in Odoo 8

I work with Odoo 8 API v8 and I want to dynamically add a domain in a field.
I have 2 classes. A mother class purchase
TMP_BESOIN = {}
TMP_BESOIN['type']= ''
_name = 'purchase.besoin'
_description = "Expression du besion d'achat"
name = fields.Char(required=True,string="Reference",default='XXX',readonly=True)
employee_id = fields.Many2one('hr.employee', string="Demandeur", required=True)
date_expression_besoin = fields.Datetime(string="Date d'expression", required=True,default=fields.Datetime.now())
demandeprix_id = fields.Many2one('purchase.demandeprix.ligne', string='Demande de prix')
lignebesoin_ids = fields.One2many('purchase.besoin.ligne','besoin_id', string='Le besoin')
type = fields.Selection([('product', 'Produit stockable'), ('consu', 'Utilisation directe'), ('immo', 'Immobilisation')],
'Type d\'articles',defaut='product')
order_ids = fields.One2many('purchase.order','besoin_id', string='Le besoin')
destination = fields.Char(string='destination')
demandeprix_ids = fields.One2many('purchase.demandeprix','besoin_id', string='ligne demande de prix')
date_reject = fields.Datetime(string="Date de rejet", readonly=True)
user_reject = fields.Many2one('hr.employee', 'Rejété par', readonly=True)
date_validate = fields.Datetime(string="Date de Validation", readonly=True)
user_validate = fields.Many2one('hr.employee', 'validé par', readonly=True)
date_authorized = fields.Datetime(string="Date de d'autorisation", readonly=True)
user_authorized = fields.Many2one('hr.employee', 'autorisé par', readonly=True)
date_wait_authorisation = fields.Datetime(string="Date de transmition pour autorisation", readonly=True)
user_wait_authorisation = fields.Many2one('hr.employee', 'Transmit par', readonly=True)
date_done = fields.Datetime(string="Date de clôture", readonly=True)
user_done = fields.Many2one('hr.employee', 'clôturé par', readonly=True)
motivation = fields.Text('Designation')
state = fields.Selection([('draft', 'Brouillon'),
('reject', 'Besoin annulé'),
('validate', 'Besoin validé'),
('stock_verified', 'Stock vérifié'),
('wait_authorized', 'En attente d\'autorisation'),
('authorized', 'Autorisé')
], 'Etat',required=True,default='draft')
_sql_constraints = [
('ref_besoin_achat_uniq', 'unique(name)', 'La reference du besoin est unique'),
]
#api.model
def create(self,vals):
if not vals.has_key('name') or vals.get('name')=='XXX':
vals['name'] = self.env['ir.sequence'].get('purchase.besoin.achat.code') or 'XXX'
return super(purchase_besoin,self).create(vals)
#api.onchange('type')
def on_change_type(self):
global TMP_BESOIN
TMP_BESOIN = {}
TMP_BESOIN['type'] = self.type
This class defined global variable TMP_BESOIN and put value in method onchange_tye
this class is in relation many2one with another classe ligne_besoin
class purchase_besoin_ligne(models.Model):
_name = 'purchase.besoin.ligne'
_description = "Ligne du besoin d'achat"
name = fields.Char('Nom', readonly=True, store=True)
besoin_id = fields.Many2one('purchase.besoin', string='Besoin', required=True, ondelete='cascade')
besoin = TMP_BESOIN.copy()
produit_id = fields.Many2one('product.product', string="Article", required=True,domain=[('product_tmpl_id.type', 'like', besoin['type'])])
qte = fields.Integer(string="Quantité", required=True,default=1)
type = fields.Selection([('product', 'Produit stockable'), ('consu', 'Utilisation directe'), ('immo', 'Immobilisation')],
'Type d\'articles',defaut=besoin['type'])
Like as in my code, I want to add a domain in produit_id, in which the value of the domain, depends on the variable type in the Mother class.
As I cannot have the value of the variable besoin_id(link with the mother classes) before calling create method. I decided to use a global Variable
The problem is that, the filter doesn't apply without an error.
try the following: assuming that type is a column of product.product in the domain of produit_id.
_name = 'purchase.besoin.ligne'
_description = "Ligne du besoin d'achat"
name = fields.Char('Nom', readonly=True, store=True)
besoin_id = fields.Many2one('purchase.besoin', string='Besoin', required=True, ondelete='cascade')
besoin = TMP_BESOIN.copy()
produit_id = fields.Many2one('product.product', string="Article", required=True,domain=[('type', 'like', besoin_id.type])])
qte = fields.Integer(string="Quantité", required=True,default=1)
type = fields.Selection([('product', 'Produit stockable'), ('consu', 'Utilisation directe'), ('immo', 'Immobilisation')],'Type d\'articles',defaut=besoin['type'])

Resources