开发者

Django - non app specific models.py?

I have multiple Django apps, and I have some code in one of my models.py that really applies to all of the apps. Is there a way to move it somewhere generic, outside of a specific app folder?

Examples of non app specific code I have:

def update_groups(sender, user=None, l开发者_高级运维dap_user=None, **kwargs):
    ...

django_auth_ldap.backend.populate_user.connect(update_groups) 

A function to correctly identify users, and connect to the correct signal.

I also have a model proxy of django.contrib.admin.models.LogEntry and a modelAdmin of that model proxy so users in the admin site can view the change history. But these really don't belong in any one app's models.py.


Well, just create a python module somewhere in your project and then refference it in your models. To do this, you need a directory with __init__.py file:

helpers/
   __init__.py 
   functions.py

Put your code into the functions.py and in any other place you will be able to:

from helpers.functions import update_groups
post_save.connect(update_groups)

Name of the module is up to you, ofcourse.


You could create a template app that could be used or extended (class hierarchy) by all your other apps that could use that code.


__init__.py in my project's directory seems to be a good place to put this stuff. It gets run right away when the server starts so it's available to everything else. It seems to work fine so far.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜