【问题标题】:Dynamically Process Stored Procedure Results With Django使用 Django 动态处理存储过程结果
【发布时间】:2021-01-05 19:41:55
【问题描述】:

我正在尝试获取存储过程的结果并动态填充模型,或者至少根据结果生成模型。

我的意图是创建一个可重用的函数,它应该对数据不明确。我不知道要返回的字段,并希望获取从存储过程返回的内容,获取字段名称并将数据放入具有所述字段名称的对象中。

如何动态发现存储过程返回的结果集中的列,然后创建要匹配的对象?

【问题讨论】:

    标签: python sql django stored-procedures


    【解决方案1】:

    我能够弄清楚这一点。我从返回的数据中得到了一个列名列表,按名称创建了一个对象,并通过字符串设置了对象的属性/属性。

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-07
      相关资源
      最近更新 更多