开发者

how to use django.core.management.sql.sql_create?

I want to use this function: django.core.management.sql.sql_create in my view, to get the "CREATE" statements

the function gets 3 arguments:

app, style, connection

what is "app"?? is it a specific object or just the app name?!

I know style is something to do with colors... I reckon django.core.management.color.colorstyle() should work..

what about connection, how do I get this one?

thanks

=========================== edited from here down

ok, after some time, I figured the things, this is what I ended up with:


def sqldumper(model):
    """gets a db model, and returns the SQL statements to build it on another SQL-able db"""
    #This is how django inserts a new record
    #u'INSERT INTO "polls_poll" ("question", "pub_date") VALUES (GE!!, 2011-05-03 15:45:23.254000)'

    result = "BEGIN;\n"
    #add CREATE TABLE statements
    result+= '\n'.join(sql_create(models.get_app('polls'), color_style(), connections.all()[0]))+"\n"
    result+= '\n'.join(sql_custom(models.get_app('polls'), color_style(), connections.all()[0]))+"\n"
    result+= '\n'.join(sql_indexes(models.get_app('polls'), color_style(), connections.all()[0]))+"\n"
    result+= '\n'

    #add INSERT INTO staetements
    units = model.objects.all().values()
    for unit in units:
        statement = "INSERT INTO yourapp.model "+str(tuple(unit.keys()))+" VALUES " + str(tuple(unit.values()))+"\n"
        result+=statement

    result+="\nCOMMIT;\n"
    return 开发者_如何学Cresult.encode('utf-8')

it's still a bit weird, because you get the CREATE TABLE for the whole app, but the INSERT INTO only for the model you ask.... but it's fixable from here


It's the models.py module found in one of your apps:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'myproject.myapp',
    )

When I printed it, I got < module 'myproject.myapp.models' from '...' >. I used the ellipses instead of typing the entire models.py file's path.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜