tags:

views:

399

answers:

4

I'm trying to reset a database in Django, using:

python manage.py reset app

but get the following error:

Error: Error: app couldn't be reset. Possible reasons:
  * The database isn't running or isn't configured correctly.
  * At least one of the database tables doesn't exist.
  * The SQL was invalid.
Hint: Look at the output of 'django-admin.py sqlreset app'. That's the SQL this command wasn't able to run.
The full error: cannot drop table app_record because other objects depend on it
HINT:  Use DROP ... CASCADE to drop the dependent objects too.

This is what my models.py file looks like:

class Record(models.Model):
    name = models.CharField(max_length=50, db_index=True)
    year = models.IntegerField(blank=True, null=True)
    def __unicode__(self):
        return self.name

class Class(models.Model):
    record = models.ForeignKey(Record)
    def __unicode__(self):
        return self.id

I get that I need to use the DROP... CASCADE command in the SQL that deletes and recreates the database (the output of django-admin.py).

But how can I edit that SQL directly from models.py?


UPDATE

OK, I figured out how to delete tables manually (the database is postgres), have noted it here for anyone with the same problem:

python manage.py dbshell 
# drop table app_record cascade; 
# \q 
python manage.py reset app

Would still like to know if anyone has a better way to do it, though :)

A: 

The problem of DROP TABLE CASCADE is that it just remove a foreign keys on related tables - after syncdb this relation is not recreated. I found no way to recreate the particular model's tables, so I'm reseting whole application by recreating schema:

  DROP SCHEMA public CASCADE;
  CREATE SCHEMA "public" AUTHORIZATION "owner of database";
HardQuestions
A: 

I use a little unix pipeline that adds CASCADE to all the DROP statements.

python manage.py sqlreset myapp | sed 's/DROP TABLE \(.*\);/DROP TABLE \1 CASCADE;/g' | \
psql --username myusername mydbname
Ryan Nowakowski
+1  A: 

The easy way to fully reset a Django database is using django-extensions.

It has a reset_db command that supports all Django's default database backends.

python manage.py reset_db

If you're using Django 1.2+ you should explicitly define the database you want to reset. If your project only uses one database, you should probably set --router=default

Henrique Bastos
A: 

Hey, my friend Jon typed this in as a slight improvement on the above:

python manage.py sqlreset users | sed 's/DROP TABLE \(.*\);/DROP TABLE \1 CASCADE;/g' | python manage.py dbshell