Search code examples
pythonodoo

How to restrict a Element with a name getting created to the Model that already have an element with the same name? Odoo 12


a = kw.get('a')           #text getting from the user input
models = request.env['htpmodel']
for model in models:
   if str(a) != str(model.name):
        h = model.create({
            'name': a,
        })

If the str of user input(a) is not in the model's name needs to be created otherwise duplicate element needs not to be created


Solution

  • I would suggest searching for the record first using the name you are supplied:

    a = kw.get("a")
    
    models = request.env["htpmodel"]
    # search to see if a record with that name already exists
    record = models.search([("name", "=", a)], limit=1)
    
    if not record:
        # the record doesn't exist
        h = model.create({
            "name": a,
        })
    

    A query to the model would be better practice than to loop through the results.

    Let me know if you need anything clarifying,

    Thanks,