2

I am writing an app in Django which has a few sitewide fixed objects I need to instantiate which, for one reason or another, can't be fixtures.

For example, some (e.g. Permissions) I can't hardcode a PK for because I can't be sure that they'll be loaded in a certain order (and if I use pk=null then I get an IntegrityError if they exist already.)

Others (e.g. Sites) depend on values in settings.py. Edit: These need to run each time the project is deployed, otherwise I could use South's data migrations as per super9's suggestion below.

Since these are Django models, they're not directly related to any of the apps in my project. It would make the most sense to load them in settings.py but that results in a circular import. It works in urls.py but putting the loading code there seems hackish and out-of-place.

I looked into hooking a receiver into post_syncdb as follows:

@receiver(post_syncdb)
def create_groups_and_permissions(sender, **kwargs):
    print "Creating groups and permissions"
    u_ct = ContentType.objects.get(model="user")
    Group.objects.get_or_create(name='Group 1')
    Permission.objects.get_or_create(name="Perm 1", codename="perm_1", content_type=u_ct)

However, since I'm using South, per the documentation it only sends post_syncdb when the table is first created. I could call syncdb manually after each time I migrate but would prefer not to.

I am nearly resolved to put them in urls.py or the most closely related app's models.py but thought I'd check here to see if there's an accepted way of loading fixed objects which can't be loaded as fixtures.

Eric P
  • 4,587
  • 6
  • 24
  • 19

1 Answers1

1

Have you checked out data migrations in south yet? http://south.aeracode.org/docs/tutorial/part3.html

Sounds like it might be what you need.

super9
  • 29,181
  • 39
  • 119
  • 172
  • Unfortunately I need these to run each time the project is deployed, and data migrations are one-and-done. This is perfect for single-creation instances though. Will update initial post to reflect this. – Eric P May 10 '12 at 04:36
  • How about writing a management command that creates the objects you need? – super9 May 10 '12 at 05:20
  • That may be the cleanest option - and just be sure to call that from my deployment process. I was hoping for something that would be automatically loaded with the project but there doesn't seem to be a clean way to do that. Thanks. – Eric P May 10 '12 at 15:17
  • You could write a bunch of commands, load it into a fabric script and run it each time you have to recreate a dev environment. That's what we my django shop. See http://docs.fabfile.org/en/1.4.2/index.html – super9 May 11 '12 at 01:19