Saturday, December 14, 2013

Re: intiial sql and foreign keys

On Fri, Dec 13, 2013 at 8:08 PM, Tom Lockhart <tlockhart1976@gmail.com> wrote:

On 2013-12-13, at 1:48 PM, Larry Martell <larry.martell@gmail.com> wrote:

I have 2 tables that I need to initialize with some initial sql files.
One table has a foreign key reference into the other. The docs say
"Note that if you have multiple SQL data files, there's no guarantee
of the order in which they're executed." So what can I do here? I
obviously need the table with the referenced data loaded first so I
can pick up the ids when I load the referencing table? How is this
situation (which seems like it would be fairly common) typlcally
handled?

If you already have the keys (that is, the table ids) assigned, then you can probably load the tables in one transaction since integrity is checked on commit.

If you need the keys assigned, then you might want to do a python script. psycopg2 can return a value which you can then stuff into your other table.

But maybe your question has a simpler answer. If you are loading SQL data directly, and not through django fixtures, you can control which table gets loaded first. Load the one with the foreign key references second.

You might need to set the next value for the sequences used for table ids if you are doing a bulk load. Something like this for pgsql:

select max(colname) from tablename;
select pg_catalog.setval('tablename_colname_seq', maxid, true);

hth


As I wrote in my initial post, I am loading the data with initial sql files (https://docs.djangoproject.com/en/1.5/howto/initial-data/#providing-initial-sql-data). I have to experiment and see what happens first - fixtures or initial sql. I may be able to do the referenced table with one and the referencing table with the other. Seems bulky though. 

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/CACwCsY6DDNQWqE%2BWqGxDcLwKW%2B78VpSHbWF9epUi8O51LkY97Q%40mail.gmail.com.
For more options, visit https://groups.google.com/groups/opt_out.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate