Django导入models.py FK错误

时间:2014-10-08 04:37:22

标签: python django django-models foreign-key-relationship

我在notifications app。

中有一个模型
class Notification(models.Model):
    name = models.CharField(max_length = 255, primary_key = True)
    description = models.CharField(max_length = 255)

Server App。

中的另一个模型
from modules.notifications.models import * # importing notification's model

class Server(models.Model):
    url = models.CharField(max_length = 255, unique = True)

    @staticmethod
    def get_as_dict(server):
        server_notification_mapping_obj = ServerNotificationMapping.objects.filter(server = server)
        notifications_list = [obj.notification.name for obj in server_notification_mapping_obj]

        return  {
                    'id':server.id, 
                    'url':server.url,
                    'notifications':notifications_list
                }




class ServerNotificationMapping(models.Model):
    server = models.ForeignKey('Server', related_name = 'servers')
    notification = models.ForeignKey('Notification',related_name = 'notifications')
    class Meta:
        unique_together = (("server", "notification"),)

即使我从Notifications应用程序导入模型,我仍然会收到错误

Unhandled exception in thread started by <function wrapper at 0x7fb523bad0c8>
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/django/utils/autoreload.py", line 93, in wrapper
    fn(*args, **kwargs)
  File "/usr/lib/python2.7/dist-packages/django/core/management/commands/runserver.py", line 101, in inner_run
    self.validate(display_num_errors=True)
  File "/usr/lib/python2.7/dist-packages/django/core/management/base.py", line 314, in validate
    raise CommandError("One or more models did not validate:\n%s" % error_text)
django.core.management.base.CommandError: One or more models did not validate:
servers.servernotificationmapping: 'notification' has a relation with model Notification, which has either not been installed or is abstract.

1 个答案:

答案 0 :(得分:1)

尝试(使用实际的类名而不是字符串):

class ServerNotificationMapping(models.Model):
    server = models.ForeignKey('Server', related_name = 'servers')
    notification = models.ForeignKey(Notification,related_name = 'notifications')
    class Meta:
        unique_together = (("server", "notification"),)