Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating models with sql data

Tags:

sql

django

models

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

like image 574
user3030969 Avatar asked Feb 24 '26 10:02

user3030969


1 Answers

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.

like image 80
Daniel Roseman Avatar answered Feb 27 '26 02:02

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!