Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
3 Trả lời
3956 Lượt xem

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!
Ảnh đại diện
Huỷ bỏ

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

Câu trả lời hay nhất

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.


Ảnh đại diện
Huỷ bỏ
Tác giả

Thank you! This is what i needed

Câu trả lời hay nhất

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

Ảnh đại diện
Huỷ bỏ
Câu trả lời hay nhất

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

Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
0
thg 3 15
7327
4
thg 6 25
11285
3
thg 4 23
54391
0
thg 3 16
6869
1
thg 8 15
12004