Что не так со следующим кодом в Python?

Я пытался реализовать ограничение для поля, но вместо того, чтобы вызывать проверку ограничения, он позволяет сохранить запись без отображения какого-либо сообщения об ограничении.

def _check_contact_number(self, cr, uid, ids, context=None):
    for rec in self.browse(cr, uid, ids, context=context):
                if rec.contact_number:
                    size=len(str(rec.contact_number))
                    if size<10:
                       return False
            if not contact_number:
            return {}
            contact_number = rec.contact_number.replace('.','') 
#removes any '.' from the string
            contact_number = rec.contact_number.replace(' ','') 
#removes space from the string
            if not  contact_number.isdigit():
            return False
        return {}

    _constraints = [
        (_check_contact_number, 'Enter valid phone number...!', 
['contact_number']),
      ]

Пожалуйста, поправьте меня. Большое спасибо


person Shravy    schedule 03.09.2015    source источник
comment
это не предупреждение?   -  person Atul Arvind    schedule 03.09.2015
comment
Осторожнее с отступом. Проверьте операторы возврата под вашими условиями.   -  person George Daramouskas    schedule 03.09.2015


Ответы (4)


Этот код имеет уродливые отступы. Может быть, это причина. Правильные иденты выглядят так:

def _check_contact_number(self, cr, uid, ids, context=None):
    for rec in self.browse(cr, uid, ids, context=context):
        if rec.contact_number:
            size=len(str(rec.contact_number))
            if size<10:
                return False
        if not contact_number:
            return {}
            contact_number = rec.contact_number.replace('.','') 
#removes any '.' from the string
            contact_number = rec.contact_number.replace(' ','') 
#removes space from the string
        if not  contact_number.isdigit():
            return False
        return {}
    _constraints = [
        (_check_contact_number, 'Enter valid phone number...!', ['contact_number']),
      ]
person Sdwdaw    schedule 03.09.2015

Предполагая

_constraints = [
    (_check_contact_number, 'Enter valid phone number...!',
['contact_number']),
      ]

правильный синтаксис и правильный отступ, это должен быть вашим кодом;

def _check_contact_number(self, cr, uid, ids, context=None):

    for rec in self.browse(cr, uid, ids, context=context):

        contact_number = rec.contact_number.replace('.','') #removes any '.' from the string
        contact_number = rec.contact_number.replace(' ','') #removes space from the string
        contact_number = rec.contact_number.replace('-','') #removes any hyphens in the string

        if rec.contact_number:
            size=len(str(rec.contact_number))
            if size<10:
                return False

        if not contact_number:
            return {}

        if not  contact_number.isdigit():
            return False
        return {}

    _constraints = [
        (_check_contact_number, 'Enter valid phone number...!',
['contact_number']),
      ]

-- Если это не сработает, нам нужно будет увидеть весь class, чтобы исправить это.

я предполагаю

_constraints = [
    (_check_contact_number, 'Enter valid phone number...!',
['contact_number']),
      ]

также неправильно расположен, что может привести к полному обрушению.

person x otikoruk x    schedule 03.09.2015

Вот более оптимизированный код для ограничения. убедитесь, что вы перезапустили сервер и обновили настроенный модуль, чтобы он вступил в силу.

def _check_contact_number(self, cr, uid, ids, context=None):
    for rec in self.browse(cr, uid, ids, context=context):
        if rec.contact_number:
            if len(str(rec.contact_number))<10:
               return False
            contact_number = str(rec.contact_number).replace('.','').replace(' ','')
            if not contact_number.isdigit():
                return False
        return True

_constraints = [
    (_check_contact_number, 'Enter valid phone number...!', ['contact_number']),
]
person Atul Arvind    schedule 03.09.2015

Некоторые другие ответы звучат разумно, вот моя попытка использовать новый API ORM Odoo:

@api.one
@api.constrains('contact_number')
def _check_contact_number(self):
    contact_number = self.contact_number.replace('.','').replace(' ','')
    if len(contact_number) < 10:
        raise exceptions.ValidationError(
            "Phone number has to contain at least 10 digits!"
        )
    if not contact_number.isdigit():
        raise exceptions.ValidationError(
            "Phone number can only contain digits, spaces and dots!"
        )

Текущий API для определения ограничений намного лучше . Вы действительно должны научиться этому. Старый API, который вы используете, устарел и в конечном итоге будет удален.

Совет Атула Арвинда о том, что нужно помнить о перезапуске сервера и обновлении конкретного модуля, также очень важен.

person Ludwik Trammer    schedule 04.09.2015