Recursive relationships in Django

By contentedweb

In my previous post I stated how I had created a recursive relationship in one mof my models. The code looks something like this:


parent = models.ForeignKey('self', blank=True, null=True)

This works great, but the problem I now faced was how to enter the root element. Even though I had sent blank and null to True I was not able to enter my root node using the default admin interface. So this is the first issue I need to solve outside of the tutorial documentation.

Ok, after some searching around it is clear that I need to update the database schema to reflect the model change. Obviously this won’t happen automatically. So I thought I could use the syncdb statement that was used to create the schema in the first place:


python manage.py syncdb

But, as it clearly says in the documentation, syncdb only creates new tables. It does not modify existing tables. The solution seems to be to run the following the statement:

python manage.py sql APP_TITLE

To see what Table schema your model is expecting and to then make the change manually in your database. Not ideal, but manageable. They are working on ways to evolve the schema via Django, but that will be for a future version I guess.

This is the first disapointing thing about Django I’ve encountered so far. The idea seems to be that you get your schema right the first time, but this seems be unrealistic to me. Especially in an agile development environment where you are likely to make small changes at a time.

Tags: , ,

4 Responses to “Recursive relationships in Django”

  1. Making database schema changes for Django « The Contented Web Blog Says:

    [...] The Contented Web Blog Creating a contented web through learning Django. « Recursive relationships in Django [...]

  2. Arien Says:

    Funny how I also ran into the same problem not too long ago :P

    Did you know about fixtures? You can dump the contents of your database, then rebuild the database and get everything added back automatically. I also started recently, and I’m constantly changing my models, while I adapt to Django’s way of the ninja. The fixtures have been working for me (except in some cases where the changes were not really compatible and I had to do it manually).

    More info:
    http://docs.djangoproject.com/en/dev/howto/initial-data/
    http://docs.djangoproject.com/en/dev/ref/django-admin/#dumpdata
    http://docs.djangoproject.com/en/dev/ref/django-admin/#loaddata-fixture-fixture

    Hope it helps :)

  3. contentedweb Says:

    Thanks Arien, these are helpful links. I’ll definitely be needing this later on so thanks for the links.

  4. Mattias Says:

    I sounds to me like django evolutions could be your fix.

    http://code.google.com/p/django-evolution/

Leave a Reply