Django: dynamic model field definition

Hi people using stackoverflow,

I have a model definition that is pretty monotonous, it includes fields for bins from 1 to 50.

To prove the concept, I wrote it manually, but there should be a better way to automate the definition of the model and keep the code in order and order.

So far, I have done this as follows:

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 = ...

In the Django wiki, I found a summary for defining dynamic models, but it doesn't seem to allow loops in the definition:

I tried the code below, but I get an error that MAX_BIN = 2 is not valid syntax. I understand a mistake that I cannot repeat across the field as 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)
    })

? , ?

!

0
2

, dict. . dict type, . -

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)
+2

, :

class Bins(models.Model):
    MAX_BIN = 50
    for i in xrange(1, MAX_BIN + 1):
        vars()['p' + str(i)] = models.DecimalField('bin ' + str(i),
            max_digits=6, decimal_places=2)
0

All Articles