def setRegister(model, rec, key, data):

    try:
        field = model._meta.get_field(key)
    except:
        return

    # Tipo de attr
    cName = field.__class__.__name__

    # Si es definido como no editable en el modelo
    if getattr(field, 'editable', False) == False:
        return
    if  cName == 'AutoField':
        return

    # Obtiene el valor
    value = data[key]

    try:

        if cName == 'CharField' or cName == 'TextField':
            setattr(rec, key, value)
            return

        elif  cName == 'ForeignKey':
            keyId = key + '_id'
            value = data[keyId]
            exec('rec.' + keyId + ' =  ' + smart_str(value))
            return

        elif cName == 'DateField':
            value = toDate(value)
        elif cName == 'TimeField':
            value = toTime(value)
        elif cName == 'DateTimeField':
            value = toDateTime(value)

        elif cName == 'BooleanField':
            value = toBoolean(value)
        elif cName == 'IntegerField':
            value = toInteger(value)
        elif cName == 'DecimalField':
            value = toDecimal(value)
        elif cName == 'FloatField':
            value = toFloat(value)

        setattr(rec, key, value)

    except Exception:
        raise Exception
def setRegister(model, rec, key, data):

    try:
        field = model._meta.get_field(key)
    except:
        return

    # Tipo de attr
    cName = field.__class__.__name__

    # Si es definido como no editable en el modelo
    if getattr(field, 'editable', False) == False:
        return
    if cName == 'AutoField':
        return

    # Obtiene el valor
    value = data[key]

    try:

        if cName == 'CharField' or cName == 'TextField':
            setattr(rec, key, value)
            return

        elif cName == 'ForeignKey':
            keyId = key + '_id'
            value = data[keyId]
            exec('rec.' + keyId + ' =  ' + smart_str(value))
            return

        elif cName == 'DateField':
            value = toDate(value)
        elif cName == 'TimeField':
            value = toTime(value)
        elif cName == 'DateTimeField':
            value = toDateTime(value)

        elif cName == 'BooleanField':
            value = toBoolean(value)
        elif cName == 'IntegerField':
            value = toInteger(value)
        elif cName == 'DecimalField':
            value = toDecimal(value)
        elif cName == 'FloatField':
            value = toFloat(value)

        setattr(rec, key, value)

    except Exception:
        raise Exception
示例#3
0
def getQbeStmt(fieldName , sQBE, sType):

    QResult = Q()

    # Valida el tipo del criterio
    if type(sQBE).__name__ in ['str', 'unicode']:
        sQBE = sQBE.strip()

        # Verifica si es una funcion
        if (sQBE and sQBE[0] == '@'):
            try:
                sQBE = doGenericFuntion (sQBE)
            except Exception as e:
                # TODO: Log error y seguimeinto para hacer nulo el Qs
                return None

        if sQBE == '' :
            return QResult

    elif type(sQBE).__name__ in ['int', 'long', 'float', 'decimal']:
        # es un numero, no hay criterios posibles solo =
        Qobj = { "{0}".format(fieldName) :   sQBE }
        return  Q(**Qobj)

    else:
        sQBE = str(sQBE)


    #  Negacion del criterio
    bNot = False
    if sQBE.startswith('!')  :
        sQBE = sQBE[1:]
        bNot = True


    # -- Para hacerlo recursivo lo que dbde controlar incialemente es el or
    if sQBE.find(";") > 0 :

        lCondicion = sQBE.split(";")
        for sCondicion in lCondicion:
            if len (sCondicion) == 0:
                continue

            bAndConector = False
            if sCondicion.startswith('!') :
                bAndConector = True
                sCondicion = sCondicion[1:]

            Qtmp = getQbeStmt(fieldName, sCondicion, sType)
            if bAndConector:
                QResult = QResult & Qtmp
            else:
                QResult = QResult | Qtmp

        if bNot :
            QResult = ~QResult
        return QResult




    # String:  \iexact, \icontains, \istartswith, isnull, search, TODO: \iendswith, \iregex
    if sType in ([ 'string', 'text', 'jsonfield' ]) :
        if sQBE.startswith('^'):
            Qobj = { "{0}__istartswith".format(fieldName) :  sQBE[1:]  }

        elif sQBE == '=' :
            Qobj = { "{0}__isnnull".format(fieldName) : True }

        elif sQBE.startswith('='):
            Qobj = { "{0}__iexact".format(fieldName) :  sQBE[1:]  }

        elif sQBE.startswith('@'):
            Qobj = { "{0}__search".format(fieldName) :  sQBE[1:]  }

        else:
            Qobj = { "{0}__icontains".format(fieldName) :  sQBE }

        QResult = Q(**Qobj)


    # TODO: Verificar q sea numerico (
    # foreignText es una simple representacion, es siempre el id
    # Numericos : gt, gte, lt, lte,   TODO: in,   range,
    elif sType in ([ 'int', 'foreignid', 'foreigntext', 'decimal' ]):

        if sQBE.startswith(">=") :
            Qobj = { "{0}__gte".format(fieldName) :  sQBE[2:]  }
        elif sQBE.startswith("<=") :
            Qobj = { "{0}__lte".format(fieldName) :  sQBE[2:]  }
        elif sQBE.startswith("<>") | sQBE.startswith("!=") :
            bNot = ~bNot
            Qobj = { "{0}".format(fieldName) :  sQBE[2:]  }

        elif sQBE.startswith(">") :
            Qobj = { "{0}__gt".format(fieldName) :  sQBE[1:]  }
        elif sQBE.startswith("<") :
            Qobj = { "{0}__lt".format(fieldName) :  sQBE[1:]  }
        elif sQBE.startswith("=") :
            Qobj = { "{0}".format(fieldName) :  sQBE[1:]  }
        else:
            Qobj = { "{0}".format(fieldName) :  toInteger(sQBE)  }

        if not isNumeric(re.sub(r'[=><!]', '', sQBE)):
            return QResult

        QResult = Q(**Qobj)

#    TODO: if sType == 'bool':
#    Fechas: year, month, day,   
#    TODO: if sType in ( [ 'date''datetime', 'time' ]) : 

    
    if bNot :
        QResult = ~QResult
    return QResult
示例#4
0
def getQbeStmt(fieldName, sQBE, sType):

    QResult = Q()

    # Valida el tipo del criterio
    if type(sQBE).__name__ in ['str', 'unicode']:
        sQBE = sQBE.strip()

        # Verifica si es una funcion
        if (sQBE and sQBE[0] == '@'):
            try:
                sQBE = doGenericFuntion(sQBE)
            except Exception as e:
                # TODO: Log error y seguimeinto para hacer nulo el Qs
                return None

        if sQBE == '':
            return QResult

    elif type(sQBE).__name__ in ['int', 'long', 'float', 'decimal']:
        # es un numero, no hay criterios posibles solo =
        Qobj = {"{0}".format(fieldName): sQBE}
        return Q(**Qobj)

    else:
        sQBE = str(sQBE)

    #  Negacion del criterio
    bNot = False
    if sQBE.startswith('!'):
        sQBE = sQBE[1:]
        bNot = True

    # -- Para hacerlo recursivo lo que dbde controlar incialemente es el or
    if sQBE.find(";") > 0:

        lCondicion = sQBE.split(";")
        for sCondicion in lCondicion:
            if len(sCondicion) == 0:
                continue

            bAndConector = False
            if sCondicion.startswith('!'):
                bAndConector = True
                sCondicion = sCondicion[1:]

            Qtmp = getQbeStmt(fieldName, sCondicion, sType)
            if bAndConector:
                QResult = QResult & Qtmp
            else:
                QResult = QResult | Qtmp

        if bNot:
            QResult = ~QResult
        return QResult

    # String:  \iexact, \icontains, \istartswith, isnull, search, TODO: \iendswith, \iregex
    if sType in (['string', 'text', 'jsonfield']):
        if sQBE.startswith('^'):
            Qobj = {"{0}__istartswith".format(fieldName): sQBE[1:]}

        elif sQBE == '=':
            Qobj = {"{0}__isnnull".format(fieldName): True}

        elif sQBE.startswith('='):
            Qobj = {"{0}__iexact".format(fieldName): sQBE[1:]}

        elif sQBE.startswith('@'):
            Qobj = {"{0}__search".format(fieldName): sQBE[1:]}

        else:
            Qobj = {"{0}__icontains".format(fieldName): sQBE}

        QResult = Q(**Qobj)

    # TODO: Verificar q sea numerico (
    # foreignText es una simple representacion, es siempre el id
    # Numericos : gt, gte, lt, lte,   TODO: in,   range,
    elif sType in (['int', 'foreignid', 'foreigntext', 'decimal']):

        if sQBE.startswith(">="):
            Qobj = {"{0}__gte".format(fieldName): sQBE[2:]}
        elif sQBE.startswith("<="):
            Qobj = {"{0}__lte".format(fieldName): sQBE[2:]}
        elif sQBE.startswith("<>") | sQBE.startswith("!="):
            bNot = ~bNot
            Qobj = {"{0}".format(fieldName): sQBE[2:]}

        elif sQBE.startswith(">"):
            Qobj = {"{0}__gt".format(fieldName): sQBE[1:]}
        elif sQBE.startswith("<"):
            Qobj = {"{0}__lt".format(fieldName): sQBE[1:]}
        elif sQBE.startswith("="):
            Qobj = {"{0}".format(fieldName): sQBE[1:]}
        else:
            Qobj = {"{0}".format(fieldName): toInteger(sQBE)}

        if not isNumeric(re.sub(r'[=><!]', '', sQBE)):
            return QResult

        QResult = Q(**Qobj)


#    TODO: if sType == 'bool':
#    Fechas: year, month, day,
#    TODO: if sType in ( [ 'date''datetime', 'time' ]) :

    if bNot:
        QResult = ~QResult
    return QResult