我不知道我是否真正理解了這個問題,但請在我的答案的評論中澄清,如果我關閉了。
# search.py
searchables = []
def search(search_string):
return [s.do_search(search_string) for s in searchables]
def register_search_engine(searchable):
if hasattr(searchable, 'do_search'):
# you want to see if this is callable also
searchables.append(searchable)
else:
# raise some error perhaps
# views.py
def do_search(search_string):
# search somehow, and return result
# models.py
# you need to ensure this method runs before any attempt at searching can begin
# like in models.py if this app is within installed_apps. the reason being that
# this module may not have been imported before the call to search.
import search
from views import do_search
search.register_search_engine(do_search)
至於在哪裏註冊您的搜索引擎,在django的信號文檔中有一些與此有關的有用文檔。
您可以將信號處理和註冊碼放在任何你喜歡的地方。但是,您需要確保它所在的模塊能夠儘早導入,以便在需要發送任何信號之前對信號進行處理。這使您的應用程序的models.py成爲註冊信號處理程序的好地方。
因此,您的models.py
文件應該是註冊您的搜索引擎的好地方。
,我只是想的備選答案:
在你settings.py
,你可以有你的聲明所有搜索功能的設置。像這樣:
# settings.py
SEARCH_ENGINES = ('app1.views.do_search', 'app2.views.do_search')
# search.py
from django.conf import settings
from django.utils import importlib
def search(search_string):
search_results = []
for engine in settings.SEARCH_ENGINES
i = engine.rfind('.')
module, attr = engine[:i], engine[i+1:]
mod = importlib.import_module(module)
do_search = getattr(mod, attr)
search_results.append(do_search(search_string))
return search_results
這工作有點類似於註冊MIDDLEWARE_CLASSES和TEMPLATE_CONTEXT_PROCESSORS。以上都是未經測試的代碼,但是如果您環顧django源代碼,您應該可以充實並刪除任何錯誤。
我不認爲你在做什麼是推薦的做法。 – 2011-02-27 09:19:53
那麼推薦的方法是什麼?如果我做錯了,我總是想學習正確的事情:) – 2011-02-27 09:30:55
這實在是一個評論,而不是問題的答案。請使用「添加評論」爲作者留下反饋。 – sloth 2012-08-15 13:42:01