3

This code

from django.db import models

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

produces these sql statements

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

I want to know if it is possible to do it the other way around. That is given a .sql file with

CREATE TABLE myapp_person (
    "id" serial NOT NULL PRIMARY KEY,
    "first_name" varchar(30) NOT NULL,
    "last_name" varchar(30) NOT NULL
);

should produce models.py file with

class Person(models.Model):
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30)

TIA

3
  • 2
    if you create the database with those tables you can then inspectdb - docs.djangoproject.com/en/dev/ref/django-admin/#inspectdb Commented Dec 9, 2013 at 14:39
  • 2
    my question is can how to create a models.py file with a .sql file. because i have a .sql file(from client) with schema and i have to make a models.py. Instead of writing all the models i want to know if there is any other way to generate models. Commented Dec 9, 2013 at 14:48
  • thanks JamesO, i now figured out what you meant. Commented Dec 9, 2013 at 16:30

1 Answer 1

2

As JamesO says in the comments, you can use inspectdb for that.

First, create a database, and run that SQL file against that database to create the tables.

Then, run python manage.py inspectdb to create the models from the database tables.

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

Comments

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.