views:

191

answers:

3

Hi,
how can I perform smth like
CREATE TABLE table_b AS SELECT * FROM table_a
using Django db API?

+1  A: 

You can't. You'll have to drop to DB-API.

Ignacio Vazquez-Abrams
You don't. You can let Django manage your DB connection still.
Oli
@Oli: Of course it manages the *connection*, but you still have to use DB-API directly, just like your answer shows.
Ignacio Vazquez-Abrams
+2  A: 

Django's ORM isn't intended for things like this. I would suggest you're doing something the wrong way but you haven't explained why you want to do this, so I can't really comment.

Anyway. You can use Django's raw SQL:

def my_custom_sql():
    from django.db import connection, transaction
    cursor = connection.cursor()

    # Data modifying operation - commit required
    cursor.execute("UPDATE bar SET foo = 1 WHERE baz = %s", [self.baz])
    transaction.commit_unless_managed()

    # Data retrieval operation - no commit required
    cursor.execute("SELECT foo FROM bar WHERE baz = %s", [self.baz])
    row = cursor.fetchone()

    return row

http://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly

Oli
Thanks. May be I'm really doing something the wrong way.Well, some values in table are evaluated according to the user's actions. And it's necessary to create check points periodically (max 2-3 check points). I intended to do it by copying table
igr
+1  A: 

As an alternative you could potentially leverage South since it has an API for creating and dropping tables.

http://south.aeracode.org/wiki/db.create_table

I haven't tried this outside the context of a migration so no guarantees it will work out-of-the-box.

Brian Luft