【问题标题】:Django import models.py FK errorDjango导入models.py FK错误
【发布时间】:2014-10-08 04:37:22
【问题描述】:

我在notifications 应用中有一个模型。

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"),)

即使我从通知应用程序导入模型,我仍然收到错误提示

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.

【问题讨论】:

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


    【解决方案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"),)
    

    【讨论】:

    • 谢谢...它工作....但是 1 个问题。会影响关系吗?另外,我还有其他 FK 关系,我在 '' 中提供了类名,那么我也应该删除它们吗?最好的做法是什么?
    • 另外,是否建议为不同的应用程序提供特定的models.py文件,或者所有模型应该组合在一个应用程序中。在不同的应用程序中有不同的模型的缺点是我对schemamigratemigrate 不同的应用程序不同。那么,推荐哪一款呢?
    • 约定是使用实际的类而不是类名的字符串。所以是的,最好对其他 FK 关系做同样的事情。不影响关系,但可能和django如何回顾类有关。
    • 是的,建议每个应用都有单独的models.py。
    猜你喜欢
    • 2016-11-11
    • 2013-08-31
    • 1970-01-01
    • 1970-01-01
    • 2011-03-07
    • 2023-03-18
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多