Django:动态模型字段定义 [英] Django: Dynamic model field definition
问题描述
Hi Stackoverflow people,
Hi Stackoverflow people,
我有一个比较单调的模型定义,它包含1到50的bin的字段。
I have a model definition which is rather monotone, it includes fields for bins from 1 to 50.
为了概念证明,我用手写了它,但必须有一个更好的方法来自动化模型定义,并保持代码的整洁。
For the proof of concept, I wrote it by hand, but there must be a better way to automate the model definition and to keep the code nice and tidy.
到目前为止,我按照这样做:
So far I did it the follow way:
class Bins(models.Model):
p1 = models.DecimalField(_('bin 1'), max_digits=6, decimal_places=2)
p2 = models.DecimalField(_('bin 2'), max_digits=6, decimal_places=2)
p3 = models.DecimalField(_('bin 3'), max_digits=6, decimal_places=2)
...
p50 = ...
在 Django wiki ,我发现动态模型定义的摘要,但它似乎不允许在定义中的循环:
On the Django wiki, I found a summary for dynamic model definitions, but its seems that it does not allow for loops in the definition:
我已经尝试了下面的代码,但是我得到一个错误msg,MAX_BIN = 2是无效的语法。
我明白我不能像我所试过的那样迭代的错误。
I have tried the code below, but I get an error msg that MAX_BIN = 2 is an invalid syntax. I understand the error that I can't iterated over the field like I tried.
Bins = type('Bins', (models.Model,), {
MAX_BIN = 50
for i in range(MAX_BIN):
name_sects = ["p", str(i)]
"".join(name_sects): model.DecimalField(_("".join([bin ', str(i)])),
max_digits=6, decimal_places=2)
})
这样的动态类定义是否可以通用?
如果是,定义课程的最佳方法是什么?
感谢您的帮助!
推荐答案
在你当前的版本中,你的循环是在一个dict的定义内。这是不允许的。但是,您可以在调用类型
之前的dict中定义您的字段,这样可以正常工作。像
in your current edition, your loop is inside the definition of a dict. that's not allowed. however, you could define your fields in a dict outside your call to type
which works fine. something like
attrs = {
other_field = models.IntegerField(),
'__module__': 'myapp.models',
}
MAX_BIN = 50
for i in range(MAX_BIN):
name_sects = ["p", str(i)]
attrs["".join(name_sects)] = model.DecimalField(_("".join(['bin ', str(i)])),
max_digits=6, decimal_places=2)
Bins = type('Bins', (models.Model,), attrs)
这篇关于Django:动态模型字段定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!