【问题标题】:Static Object Class / Keys as ForeignKey in Django Model静态对象类/键作为 Django 模型中的 ForeignKey
【发布时间】:2011-05-20 00:57:34
【问题描述】:

我进入了 Django/Python 的新领域。我正在构建一个站点,用户从可用服务列表中进行选择,然后输入有关服务的信息。

我不想将服务列表保留在数据库中,因为这实际上是更多的站点配置信息而不是用户信息。所以我将它们设置为一个对象类(由朋友推荐)

class Service(object):
    def __init__(self, name, sections, link,  enabled=True):
        self.name = name
        self.link = link
        self.sections = sections
        self.enabled = enabled

SERVICES = {
    'SERVICE1': ArtistService(
        'Service Name',
        ['Section Name 1','Section Name 2',],
        'http://www.service.com',
    ),

是否可以将此类用作数据库中的外键?我想通过模板连接从类中检索有关服务的一些信息。示例:

{% for s in user_activated_services %}
    {{ s.service.name }}    
{% endfor %}

但它不起作用,因为我只是将密钥保存在 user_activated_services 模型的 CharField 中:

class ActivatedServices(models.Model):
    user_page = models.ForeignKey(Page)
    service = models.CharField(max_length=20, choices=[(k, s.name) for k, s in userservices.services.SERVICES.iteritems()])

当我尝试用外键替换时,我收到错误消息“ForeignKey 的第一个参数必须是模型、模型名称或字符串 'self'”

无论如何,我想我知道问题所在,但我无法解决它。希望这是足够的信息。我确定我错过了一些愚蠢的东西。

提前致谢。

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    是否可以将此类用作数据库中的外键?

    没有。

    只有models.Model 类可以用作外键。

    “外键”是一个数据库概念。

    如果您想将非数据库内容作为外键,它们只是字符串或数字,而“引用”是在代码中管理的简单映射。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-15
      • 1970-01-01
      • 2014-07-23
      • 1970-01-01
      • 1970-01-01
      • 2011-08-21
      • 1970-01-01
      相关资源
      最近更新 更多