I need to create models of existing previously unknown tables. Others have had said to
You can look at inspectdb code, and instead of outputting code return classes.
but for a python newbie I am having difficulties. Could anyone offer a more concrete example on how to do this? Many thanks.
UPDATE: I am exploring this. Looks v promising. There seem to be several options for creating dynamic models, some of which though require non- mySQL dbs (see this stackoverflow Q)
UPDATE2: I can now create a model of a previously unknown mysql table at runtime using the below functions. When I try to query the model though, for a table called 'table1' I get "Table 'djangodb.subscription_table1' doesn't exist"). When I rename 'table1' to 'subscription_table1' I get this error: "Table 'djangodb.subscription_subscription_tb2f1e1e47d73417ab2b187bc4a08bf57' doesn't exist").
HELP!
FINAL UPDATE: I went with another solution for my particular problem: Django - List of Dictionaries to Tables2
def getModel(table_name):
myColumns=getColumns(table_name)
attrs = {}
attrs['__module__'] = 'subscription.models'
for x,y in myColumns.items():
fieldType = y["type"]
if x == 'id': ''
elif fieldType == "char": attrs[x]=models.CharField(max_length='length')
elif fieldType == "float": attrs[x]=models.FloatField(max_length='length')
elif fieldType == "int": attrs[x]=models.IntegerField()
elif fieldType == "text": attrs[x]=models.TextField()
else: print "AW PROB in exptDB---------------",x,y["type"],y["length"]
myModel = type(str(table_name), (models.Model,), attrs)
return myModel
def getColumns(expt_id):
cursor = connection.cursor()
cursor.execute("desc %s;" % (expt_id))
exptInfo = str(cursor.fetchall())[1:-1]
myList= exptInfo.split("""(u'""")
myColumns = {}
for item in myList:
mySplit = item.replace("u'","").replace("'","").replace(" ","").split(",")
if len(mySplit)>=2:
subSplit=mySplit[1].split("(")
if len(subSplit)>=1:
subSplit.append('999')#does not latter.
myColumns[mySplit[0]]={"type":subSplit[0],"length":subSplit[1].replace(")","")}
return myColumns