Restore data for a specific app only

My Django project consists of several apps. Now I want to restore all data for one specific app only.

The PostgreSQL database contains severals tables with the prefix “appname_”. I can delete these tables with psql like so: drop table appname_table_one table_two etc.

Now I can restore these tables (one by one):

pg_restore -h <host_name> -p 10077 -U <user_name> --no-owner -d <database_name> -t <table_name> backupfile.dump

I’m afraid that’s not enough for a consistent restore, is it?

That depends upon the relationships that may exist in your data between apps. If you have any foreign keys relating entries in to or from this app to models in different apps, then you may have problems.

(Simple example: Say you have a model that has a foreign key to the User model. If you’ve deleted a user between the time the backup was taken and when you’re doing this restore, your backup will still have a reference to that now-invalid object.)

So it’s really a question of understanding the relationships in your data.

1 Like

The app still works after restoring the data, but it’s very slow, because the indexes are missing. The documentation of pg_restore explains:

(…) while pg_dump’s -t flag will also dump subsidiary objects (such as indexes) of the selected table(s), pg_restore’s -t flag does not include such subsidiary objects.

Obvisiously, you have to add these indexes manually, one by one, see postgresql - restoring table with pg_restore does not include primary key or indexes - Stack Overflow

For me, in my case, it’s a bit too tedious (and I fear to forget some indexes or to do something else wrong), so I won’t do that but simply redo the couple of changes in my data itself manually. Nevertheless it would be interesting to know if there is an easier (and safer) way to restore a backup of one specific app, just in case.

You’d have to build such a process yourself.

Keep in mind that what you’re thinking of as an “app” in Django does not define anything other than a naming convention for objects within PostgreSQL. Those apps have no physical significance within the database.

So, you could create your own backup process that performs separate backups for each app. Or you could do your full database backup and then separate out the portions you’d want to restore.