如何使用 Django 将 python 类存储到数据库中?
我有两个文件:
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 类存储到数据库中的最佳方法是什么?
请原谅我糟糕的英语。如果您需要更多信息,请告诉我。 ;-)
I have two files:
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)
The problem: classes from choices.py need something like a primary key to be stored in my database. Here I write these keys (1, 2, ...) by hand, but this is ugly.
For instance, I don't want to do that:
class SomeChoice:
id = 1
name = "lorem"
class AnotherChoice:
id = 2
name = "lorem"
So my question is: what is the best way to store python classes into a database ?
Please excuse my ugly english. If you need more informations, just tell me. ;-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 pickle 来存储类的实例,但这样会更难看,并且在这种情况下您不需要将类存储在数据库中,所以不要(您想要尽可能避免访问数据库)。
为了避免在两个地方重复 ID,您可以将代码更改为以下内容:
choices.py
models.py< /强>
You could use pickle to store instances of the classes, but then it would be uglier, and you don't need to store the classes in the database in this case, so don't (you want to avoid hitting the database as much as possible).
To avoid repeating the IDs in two places, you could change the code to something like that:
choices.py
models.py
SomeChoice 和 AnotherChoice 类的价值是什么?为什么不将键和值存储在字典中(SomeModel 中的一种链接 CHOICES)并创建一个仅代表一种选择的新类,
然后您将获得与 SomeChoice 和 AnotherChoice 相同的功能,但如果您添加更多选择,你不需要更多的课程。也许您的示例过于简单,但我没有看到这些类的价值。抱歉,如果我完全没有抓住要点。
What's the value of the SomeChoice and AnotherChoice classes? Why not just store the keys and values in a dictionary (kind of link CHOICES in your SomeModel) and have one new class that just represents a choice,
and then you get the same functionality of your SomeChoice and AnotherChoice, but if you add more choices, you don't need more classes. Maybe your example was just over-simplified, but I don't see the value of those classes. Sorry if I missed the point completely.