igr
igr

Reputation: 23

Create or copy table dynamically, using Django db API

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

Upvotes: 2

Views: 2062

Answers (3)

Brian Luft
Brian Luft

Reputation: 1173

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.

Upvotes: 3

Oli
Oli

Reputation: 239810

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

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798656

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

Upvotes: 1

Related Questions