gpt4 book ai didi

python - 如何使用 Django 将 python 类存储到数据库中?

转载 作者:搜寻专家 更新时间:2023-10-30 20:13:25 25 4
gpt4 key购买 nike

我有两个文件:

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 类存储到数据库中的最佳方法是什么

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

最佳答案

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

关于python - 如何使用 Django 将 python 类存储到数据库中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2213402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com