Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - Dynamically Process Stored Procedure Results With Django

I am attempting to get the results of a stored procedure and populate a model dynamically, or at a minimum, generate a model based off of the result.

My intent is to create a reusable function where it should be ambiguous to the data. I will not know the fields being returned, and wish to take what's returned from the stored procedure, get the field names and put the data in an object with said field names.

How can I dynamically discover the columns in a result set returned from a stored procedure and then create an object to match?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I was able to figure this out. I got a list of the column names from the returned data, created an object by name and set properties/attributes of the object by string.

def callProc(sqlString, clsName):
    cursor = connection.cursor()  
    dataResults = []
      
    try:
        cursor.execute(sqlString)        

        #get data results
        results = cursor.fetchall()

        #Get column names
        columns = [column[0] for column in cursor.description]                   
        #populate class
        for row in results:
            p = getattr(sys.modules[__name__], clsName)
            i=0
            for x in columns:
                #set property value of matching column name
                setattr(p, x, row[i])
                #get property value
                #x = getattr(p, x)
                i=i+1
            dataResults.append(p)
    except Exception as ex:
        print(ex)
    finally:
        cursor.close()

    return dataResults

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...