开发者

Django: Force table creation order on syncdb

I have a Profile model that is used to define a profile for a User from the auth application. Also, I have a signal that will create an empty profile each time a user is created.

The problem is that, when starting from clean, the Profile table is created after the User table, so,开发者_如何学编程 when I am asked to add the super user, my signal function fails, because there is no Profile table to enter the empty profile.

Is there a way to force in which order the tables should be created by the syncdb, so that the profile table should already be created when the super user is added ?


Do one of the following:

  1. Modify your signal to catch this specific error (table does not exist) and ignore it. Won't help if you need to have Profile for superuser too.

  2. Do not insert any data before whole DB schema is initialized. You don't have to create superuser during syncdb, this can be done later from dev console (django-admin.py shell) or you could put superuser's User and Profile to your app's initial_data.json fixture that is loaded automatically during syncdb. This will reset it's information on ever syncdb, but in certain cases it's acceptable.

  3. Use AutoOneToOneField from django-annoying lib to automatically create Profile the first time it's accessed. This is how I'd solve this problem myself -- no need to redo existing functionality with signals. Here's an example from their wiki:

    from annoying.fields import AutoOneToOneField
    
    class MyProfile(models.Model):
        user = AutoOneToOneField(User, primary_key=True)
    


The order in which the tables are created depends on the order in which you have them in your INSTALLED_APPS

Try moving your app with Profile above django.contrib.auth

Unless you are using a database with Foreign Key checks, in which case the User table may need to be first.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜