Overslaan naar inhoud
Menu
Je moet geregistreerd zijn om te kunnen communiceren met de community.
Deze vraag is gerapporteerd
3 Antwoorden
3490 Weergaven

I have a many2many field and in some cases, that field should only have 1 line. I don't want to create a separate field for that condition since i'll be using it to my other modules. So how can i restrict user to add another line if they already selected 1?


this doesn't work:








Thank you!
Avatar
Annuleer

You always can put a domain for your conditions,
field_m2o = FIelds.Many2one('my.model',domain=[('your_condition','=',value')])

Beste antwoord

To restrict the user from adding more than one line in a Many2many field in Odoo, you can use a Python constraint on the model to validate the number of selected lines. Here's an example of how you can achieve this:

from odoo import models, fields, api
from odoo.exceptions import ValidationError

class MyModel(models.Model):
_name = 'my.model'

many2many_field = fields.Many2many('other.model', 'my_model_other_model_rel')

@api.constrains('many2many_field')
def _check_many2many_field_lines(self):
for record in self:
if len(record.many2many_field) > 1:
raise ValidationError('You can only select one line in the Many2many field.')


In this example, `my.model` represents the model where you have the Many2many field, and `other.model` is the model that the Many2many field is referencing.

The `@api.constrains` decorator is used to define a constraint on the `many2many_field` field. In the constraint method `_check_many2many_field_lines()`, we iterate over the records and check if the number of selected lines is greater than 1. If it is, we raise a `ValidationError` with an appropriate error message.


Avatar
Annuleer
Auteur

Thank you! This is what i needed

Beste antwoord

btw your code is note visible,check this video how to pass your code in odoo forum
https://www.youtube.com/watch?v=nw3q0Cs1swg&ab_channel=OdooMates

Avatar
Annuleer
Beste antwoord

Hi

Try this code and follow the documentation:

many2many_field = fields.Many2many('related.model', limit=1)

OR

many2many_field = fields.Many2many('related.model', domain=[('condition',=, 'value')]

Also, check if there is a record already added in the field. If not then just add it to the field.

Hope it helps

Avatar
Annuleer
Gerelateerde posts Antwoorden Weergaven Activiteit
0
mrt. 15
6909
3
apr. 23
53546
3
mrt. 21
10278
0
mrt. 16
6447
1
aug. 15
11722