Login

Table Creation Using ORM Standalone

Author:
EliAndrewC
Posted:
February 19, 2008
Language:
Python
Version:
.96
Score:
2 (after 2 ratings)

I love the Django templates and ORM, but I prefer to use CherryPy as my web server. So I want to be able to do the equivalent of "python manage.py sql" but without actually needing to have a Django application. So I stick all of my models in a file named "models.py" and then run this script and it prints out all of the CREATE TABLE statements for my database.

 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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 12 months ago

Comments

Please login first before commenting.