10

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})
Gopi
  • 216
  • 1
  • 3
  • 11

2 Answers2

33

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

Reference

Max
  • 1,528
  • 21
  • 33
6

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

arocks
  • 2,862
  • 1
  • 12
  • 20
  • Hey thanks for the link. I've tried doing it. The call never ends. I waited for more than an hour. It is running forever. I have around ten tables and cumulatively 2500 rows. Is there a way to know if the inspectdb is working? – Gopi Feb 11 '14 at 09:00