【问题标题】:How to store python classes into a database with Django?如何使用 Django 将 python 类存储到数据库中?
【发布时间】:2011-01-13 21:05:58
【问题描述】:

我有两个文件:

choices.py

class SomeChoice:
    name = u"lorem"

class AnotherChoice:
    name = u"ipsum"

# etc...

models.py

from django.db import models
import choices

class SomeModel(models.Model):
    CHOICES = (
        (1, choices.SomeChoice.name),
        (2, choices.AnotherChoice.name),
        # etc...
    )
    somefield = models.IntegerField('field', choices=CHOICES)

问题:choices.py 中的类需要存储在我的数据库中的主键之类的东西。这里我手动写了这些键(1, 2, ...),但这很难看。

例如,我不想这样做:

class SomeChoice:
    id = 1
    name = "lorem"

class AnotherChoice:
    id = 2
    name = "lorem"

所以我的问题是:将 python 类存储到数据库中的最佳方法是什么

请原谅我丑陋的英语。如果您需要更多信息,请告诉我。 ;-)

【问题讨论】:

    标签: python database django django-models storing-information


    【解决方案1】:

    您可以使用 pickle 来存储类的实例,但这样会更难看,并且在这种情况下您不需要 将类存储在数据库中,所以不要 (您希望尽可能避免访问数据库)。

    为避免在两个地方重复 ID,您可以将代码更改为以下内容:

    choices.py

    _registry = {}
    
    def register(choice_class):
        id = len(_registry) + 1
        choice_class.id = id
        _registry[id] = choice_class
    
    def as_list():
        ret = []
        for id in sorted(_registry):
            ret.append((id, _registry[id].name))
        return ret
    
    def get_choice(id):
        return _registry[id]
    
    class SomeChoice:
        name = u"lorem"
    
    class AnotherChoice:
        name = u"ipsum"
    
    register(SomeChoice)
    register(AnotherChoice)
    

    models.py

    from django.db import models
    import choices
    
    class SomeModel(models.Model):
        somefield = models.IntegerField('field', choices=choices.as_list())
    

    【讨论】:

    • 这是个好主意,谢谢!但是仍然存在一个问题:在您的示例中,如果(出于任何原因)我决定删除 register(SomeChoice),则所有 (key,class) 对都将被更改。但是我需要为每个类设置一个 uniquepermanent 键。实际上问题应该是:有没有办法为一个类创建一个唯一键(自然数,非零)?
    • 您可以调整注册模式以将注册表存储在一个文件中,并且仅当一个类以前从未见过时才生成一个新 ID,按模块名称 + 名称对类进行索引(并注意并发问题)...或者你可以在 register() 调用上方写# Don't touch! ;)
    • 我是个懒人,所以目前我会使用第二个选择。非常感谢您的帮助。 :)
    【解决方案2】:

    SomeChoice 和 AnotherChoice 类的价值是什么?为什么不直接将键和值存储在字典中(SomeModel 中的一种链接 CHOICES)并拥有一个仅代表选择的新类,

    class UserChoice:
        def __init__(self, id, name):
            self.id = id
            self.name = name
    

    然后您将获得与 SomeChoice 和 AnotherChoice 相同的功能,但如果您添加更多选择,则不需要更多类。也许您的示例过于简单,但我看不到这些类的价值。对不起,如果我完全错过了重点。

    【讨论】:

      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 1970-01-01
      • 2014-08-21
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2019-03-03
      • 1970-01-01
      相关资源
      最近更新 更多