简体   繁体   English

静态对象类/键作为Django模型中的ForeignKey

[英]Static Object Class / Keys as ForeignKey in Django Model

I'm in new territory with Django/Python. 我在使用Django / Python的新领域。 I'm building a site where the user selects from a list of available services, and then enters info about the services. 我正在建立一个站点,用户在该站点中从可用服务列表中进行选择,然后输入有关服务的信息。

I didn't want to keep the service list in the database, becasue that's really more site configuration info rather than user info. 我不想将服务列表保留在数据库中,因为实际上更多的是站点配置信息,而不是用户信息。 So I'm setting them as an Object Class (recommended by a friend) 所以我将它们设置为对象类(朋友推荐)

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

Is it possible to use this class as a foreign key in the database? 是否可以将此类用作数据库中的外键? I'd like to retreive some information about the service from the class though a template join. 我想通过模板联接从该类中检索有关该服务的一些信息。 Example: 例:

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

But it's not working because I'm just saving the key in a CharField in the user_activated_services model: 但这不起作用,因为我只是将密钥保存在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()])

When I try to replace with a foreign key, I get an error of "First parameter to ForeignKey must be either a model, a model name, or the string 'self'" 当我尝试用外键替换时,出现错误“外键的第一个参数必须是模型,模型名称或字符串'self'”

Anyway, I think I know the problem, I just can't fix it. 无论如何,我想我知道问题所在,但我无法解决。 Hope this is enough info. 希望这是足够的信息。 I'm sure I'm missing something stupid. 我确定我想念一些愚蠢的东西。

Thanks in advance. 提前致谢。

Is it possible to use this class as a foreign key in the database? 是否可以将此类用作数据库中的外键?

No. 没有。

Only models.Model classes can be used as foreign keys. 只有models.Model类可以用作外键。

"Foreign Key" is a database concept. “外键”是一个数据库概念。

If you want to have non-database things as foreign keys, they're just strings or numbers and the "reference" is a simple mapping that you manage in your code. 如果要将非数据库对象作为外键,则它们只是字符串或数字,而“引用”是在代码中管理的简单映射。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM