0

我无法从我的“核心”应用程序导入我的模型“LogDBEvents”......这是我的项目的层次结构:

1/var/www/arpaso (root of the project)
    2/core
        3/signals
            4/__init__.py
            4/log_db_event.py
        3/__init__.py
        3/models.py
    2/manage.py

正如我在其他帖子中所读到的,它可能是一个循环引用:

 File "/var/www/arpaso/core/models.py", line 2, in <module>
    from core.signals.log_db_event import save_handler, del_handler
  File "/var/www/arpaso/core/signals/log_db_event.py", line 1, in <module>
    from core.models import LogDBEvents
ImportError: cannot import name LogDBEvents

如果是这样,如何解决?这是我的两个文件:

模型.py:

from django.db import models
from core.signals.log_db_event import save_handler, del_handler
from django.db.models.signals import post_save, post_delete

#Q10 create model to store database events
class LogDBEvents(models.Model):
    EVENTS= (
        ('DC','Database entry created'),
        ('DD','Database entry deleted'),
        ('DE','Database entry edited'),
    )
    event_time = models.DateTimeField(auto_now_add=True)
    event_type = models.CharField(choices=EVENTS, max_length=2)
    info = models.TextField()


#start a listener for INSERT INTO or UPDATE queries
post_save.connect(save_handler, dispatch_uid='post_save')
#start a listener for DELETE queries
post_delete.connect(del_handler, dispatch_uid='post_delete')

log_db_event.py:

from core.models import LogDBEvents


#Q10: saves a signal into the database
def log_handler (signal_type, sender, **kwargs):
    #do not save events from LogDBEvents (otherwise unfinite calls!)
    if sender != LogDBEvents:
        LogDBEvents(event_type=signal_type,
                info="%s model changed with new entry %s"%(
                        sender.__name__,
                        kwargs['instance'])
        ).save()

#Q10: a create or add signal is intercepted
def save_handler(sender, **kwargs):
    if kwargs['created']:
        return log_handler ('DC', sender, **kwargs)
    else:
        return log_handler ('DE', sender, **kwargs)

#Q10: a delete signal is intercepted
def del_handler(sender, **kwargs):
    return log_handler ('DD', sender, **kwargs)
4

1 回答 1

0

我最终使用了这种方法:

log_db_event.py:

import core.models
instance=core.models.LogDBEvents()

有用 ;)。

于 2013-08-26T04:43:30.353 回答