如何用Django将Python类存入数据库?

4 投票
2 回答
3215 浏览
提问于 2025-04-15 18: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类存储到数据库的最佳方法是什么

请原谅我英语不好。如果你需要更多信息,随时告诉我。;-)

2 个回答

0

SomeChoice和AnotherChoice这两个类有什么用呢?为什么不直接把键和值存储在一个字典里(就像在你的SomeModel中链接CHOICES那样),然后只用一个新类来表示一个选择呢,

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

这样你就能得到和SomeChoice、AnotherChoice一样的功能,而且如果你想添加更多的选择,就不需要再创建更多的类了。也许你的例子只是过于简单化了,但我看不出这些类的价值。如果我完全没理解你的意思,真是抱歉。

4

你可以用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())

撰写回答