Reputation: 216
I have created a django project and now rendering templates. I have a mysql database already with loads of tables and data.
From what i saw in the tutorials, the model concept of python is interesting and easy however i am not able to use it here, as i have no models available i guess. Was assuming django would magically create models based on my db.
I have filled up settings.py with engine, db, username, host, port etc., Do i have to create models based on my tables?
This works thou:
db = MySQLdb.connect(user='root', db='dbBooks', passwd='1234', host='localhost')
cursor = db.cursor()
cursor.execute('SELECT bookname FROM books')
names = [row[0] for row in cursor.fetchall()]
db.close()
return render(request, 'index.html', {'bookNames': names})
Upvotes: 10
Views: 18081
Reputation: 1548
inspectdb
works fine now. (Django 1.7.1) Simply running manage.py inspectdb will create classes for all tables in database and display on console.
$ python manage.py inspectdb
Save this as a file by using standard Unix output redirection:
$ python manage.py inspectdb > models.py
Upvotes: 33
Reputation: 2882
There is an way by which Django will auto-magically create models based on tables using the inspectdb option of manage.py
. A short guide is provided in Django Documentation itself on Integrating Django with a legacy database
Upvotes: 6