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. Permission
s) 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. Site
s) 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.