Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to use my existing mysql database with django

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})
like image 949
Gopi Avatar asked Feb 10 '14 16:02

Gopi


1 Answers

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

like image 184
Max Avatar answered Oct 19 '22 18:10

Max