Table Creation Using ORM Standalone

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""
usage: python creates.py [MODEL_1] [MODEL_2] ... [MODEL_N]

Prints CREATE TABLE statements for all models in the models.py file found in the same directory as this script.  If extra command line arguments are provided, it only prints the CREATE TABLE statements for those models.
"""

import models
from sys import argv
from django.core.management.sql import sql_model_create
from django.db.models import Model
from django.db.models.base import ModelBase

classes = [thing for thing in models.__dict__.values() if type(thing) is ModelBase]

class Style:
    def __getattr__(self, name):
        return lambda text: text

classes.remove(Model)
if len(argv)>1:
    classes = [c for c in classes if c.__name__ in argv[1:]]

print("")
for model in classes:
    print("DROP TABLE IF EXISTS _"+model.__name__.lower()+";")
    print( sql_model_create(model, Style(), classes)[0][0] )
    print("")

More like this

  1. Binding pre-existing tables with dynamically created class models by rodsenra 4 years, 7 months ago
  2. Ordered items in the database - alternative by Leonidas 4 years, 8 months ago
  3. Dynamic Models Revisited by Ben 4 years, 4 months ago
  4. Querying on existence of a relationship by ubernostrum 4 years, 6 months ago
  5. db_dump.py - for dumpping and loading data from database by limodou 4 years, 11 months ago

Comments

follower (on July 28, 2009):

It seems like this doesn't work anymore with Django 1.0 (primarily due to absence of sql_model_create).

I got pretty much the same results with this:

## With directory layout:

settings.py
orm/
    __init__.py
    models.py

## With content:

# settings.py
DATABASE_ENGINE="sqlite3"
DATABASE_NAME="database_name.db"

INSTALLED_APPS = ('orm')

# models.py
from django.db import models

class SomeModel(models.Model):

Then running either of the following commands:

django-admin.py sqlall --settings=settings --pythonpath=. orm

django-admin.py syncdb --settings=settings --pythonpath=.

See here for further details

#

(Forgotten your password?)