dumpdata and self referencing foreign keys

277 views
Skip to first unread message

Michael Elkins

unread,
Jan 6, 2012, 10:47:45 AM1/6/12
to django...@googlegroups.com
I have a model which represents a tree structure using a foreign
key to itself:

class Foo(models.Model):
name = models.CharField(max_length=30)
parent = models.ForeignKey('Foo')

My problem is that "django-admin dumpdata" does not sort the rows
such that it avoids forward references for the foriegn key values,
which is a problem since I'm using MySQL InnoDB tables. I see
that this problem seems to be fixed in the devel tree
(https://code.djangoproject.com/ticket/3615), but I just wanted to
make sure there wasn't something I could easily do in the interim.

Since I know there are no circular references, I can write a
script to postprocess the dumpdata output and reorder to avoid
forward references.

Is there an easier alternative that I've missed?

Thanks!

me

Michael Elkins

unread,
Jan 6, 2012, 4:24:20 PM1/6/12
to django...@googlegroups.com
On Fri, Jan 06, 2012 at 07:47:45AM -0800, Michael Elkins wrote:
>My problem is that "django-admin dumpdata" does not sort the rows such
>that it avoids forward references for the foriegn key values, which is
>a problem since I'm using MySQL InnoDB tables. I see that this
>problem seems to be fixed in the devel tree
>(https://code.djangoproject.com/ticket/3615), but I just wanted to
>make sure there wasn't something I could easily do in the interim.
>
>Since I know there are no circular references, I can write a script to
>postprocess the dumpdata output and reorder to avoid forward
>references.

For future reference, I found a couple of interesting things:

If the model has "ordering = ('id',)" in its Meta, forward
references will be avoided because the objects will be listed in
the order they were created
http://www.pragmar.com/2010/01/16/django-dumpdataloaddata-import-errors-on-recursive-model/

The django-data-tools app
(http://pypi.python.org/pypi/django-data-tools/0.1) enhances the
dumpdata command in django-admin to deal with sorting tables by
dependencies, including self-references.

I ended up creating a script using Django's serialization directly
to create a dump of my table that can be imported with loaddata:

from django.core import serializers
import models

print serlializers.serialize('json', models.Foo.objects.all().ordered_by('id'), use_natural_keys=True)

Reply all
Reply to author
Forward
0 new messages