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})

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.